如何检查光标是否在元素上?

时间:2010-08-03 09:42:41

标签: javascript jquery

如何使用JQuery / Javascript检查光标是否在html页面上的div上?

我正在尝试获取光标坐标以查看它们是否在我元素的矩形中。也许有预定义的方法?

UPD,不要对hover事件等做任何说明。我需要一些方法,它会为页面上的某些元素返回true / false,如:

var result = underElement('#someDiv'); // true/false

5 个答案:

答案 0 :(得分:10)

我不确定你为什么要避免如此糟糕地悬停:考虑以下脚本

$(function(){

    $('*').hover(function(){
        $(this).data('hover',1); //store in that element that the mouse is over it
    },
    function(){
        $(this).data('hover',0); //store in that element that the mouse is no longer over it
    });


    window.isHovering = function (selector) {
        return $(selector).data('hover')?true:false; //check element for hover property
    }
});

基本上,我们的想法是你使用悬停在鼠标悬停在它上面/不再在它上面的元素上设置一个标志。然后你编写一个检查该标志的函数。

答案 1 :(得分:8)

为了完整起见,我将添加一些我认为会对性能有所帮助的更改。

  1. 使用委托将事件绑定到一个元素,而不是将其绑定到所有现有元素。

    $(document).on({
      mouseenter: function(evt) {
        $(evt.target).data('hovering', true);
      },
      mouseleave: function(evt) {
        $(evt.target).data('hovering', false);
      }
    }, "*");
    
  2. 添加jQuery伪表达式:hovering

    jQuery.expr[":"].hovering = function(elem) {
      return $(elem).data('hovering') ? true : false; 
    };
    
  3. 用法:

    var isHovering = $('#someDiv').is(":hovering");
    

答案 2 :(得分:3)

最简单的方法可能就是始终跟踪鼠标所在的元素。尝试类似:

<div id="1" style="border:solid 1px red; width:50px; height:50px;"></div>
<div id="2" style="border:solid 1px blue; width:50px; height:50px;"></div>
<div id="3" style="border:solid 1px green; width:50px; height:50px;"></div>

<input type="hidden" id="mouseTracker" />

​$(document).ready(function() {
    $('*').hover(function() { 
        $('#mouseTracker').val(this.id);
    });
});

然后你的功能就是

function mouseIsOverElement(elemId) {
    return elemId === $('#mouseTracker').val();
}

答案 3 :(得分:2)

你能不能检查$(select).is(':hover')?

答案 4 :(得分:1)

我使用自定义功能执行此操作:

$(document).mouseup(function(e) { 
     if(UnderElement("#myelement",e)) {
         alert("click inside element");
     }
});

function UnderElement(elem,e) {
     var elemWidth = $(elem).width();
     var elemHeight = $(elem).height();
     var elemPosition = $(elem).offset();
     var elemPosition2 = new Object;
     elemPosition2.top = elemPosition.top + elemHeight;
     elemPosition2.left = elemPosition.left + elemWidth;

     return ((e.pageX > elemPosition.left && e.pageX < elemPosition2.left) && (e.pageY > elemPosition.top && e.pageY < elemPosition2.top))
 }
相关问题