如何检查鼠标是否悬停在元素上?(jQuery)

7

如何检查鼠标是否悬停在一个元素上?

我移动元素到鼠标位置并需要检查鼠标是否悬停在另一个元素上。如何实现?

<div class="dragged"></div> // I can move it
<div class="dropped"></div> // Need to drop here

$('.dragged').mousemove(function(e) {
   ...
   if($(".dropped").is(":hover")) { // of course doesn't work
        ...
   }
});

感谢您的提前帮助。

如果您正在使用jQuery UI的draggable/droppable,您可以检查drop事件的ui参数:http://api.jqueryui.com/droppable/#event-drop - Rory McCrossan
也许你可以使用 .mouseover?http://api.jquery.com/mouseover/ - GCallie
@RoryMcCrossan,抱歉我不使用它。 - qwerty
5个回答

9
你可以尝试以下方法:

您可以尝试以下方法:

$('#test').click(function() {
    if ($('#Test').is(':hover')) {
        alert('Test');
    }
});

JS FIDDLE DEMO


我将元素(.dragged)移动到光标位置,并且它将始终悬停。 - qwerty

3
一种有效的方法是在鼠标进入时“标记” .dropped 标签元素。最后,当你移动 .dragged 时,你可以检查 .dropped 是否有你放入其中的标记。
$('.dropped').hover(function() { 
  $(this).addClass('hovered');
}, function() {
  $(this).removeClass('hovered');
});

$('.dragged').mousemove(function(e) {
  ...
  if($(".dropped").hasClass(".hovered")) {
    ...
 }
});

致敬。


3
尝试这个:
  var hovred=null;
    $('.dropped').mouseenter(function(e) {
      hovred=$(this);
     });

$('.dropped').mouseleave(function(e) {
  hovred=null;
 });
$('.dropped').mousemove(function(e) {
   ...
   if($(this)==hovred && hovred != null) { 
    //do your stuff here man
   }
});

0
做类似这样的事情。
 var $container = $('.container');
 $container.mouseenter(function(e) {
  //do something
 });

1
谢谢,但是它不会起作用,因为靠近鼠标的位置已经有元素了。(被拖动的元素) - qwerty
又一个有趣的 bug:Safari 生成 mouseenter/mouseleave 事件时会将 box-shadow 视为元素的一部分。 - Adam Leggett

0
<script type="text/javascript">
function call_mouseover()
{ 
  alert("mouse is over on the div");
}
function call_mouseout()
{
 alert("mouse out from the div");

}
</script>


<div class="dragged" onmouseover="call_mouseover();" onmouseout="call_mouseout();"></div>
<div class="dropped" ></div> // Need to drop here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接