【问题标题】:jQuery - How to check which element is being hovered over (but NOT any specific element!)jQuery - 如何检查悬停在哪个元素上(但不是任何特定元素!)
【发布时间】:2012-01-18 19:14:46
【问题描述】:

我想使用 jQuery 来确定当前悬停在哪个元素上。它可以是页面上的任何元素,这意味着 mouseovermouseoutmouseentermouseleave 不适用于此处,因为它们与特定元素相关。

这是一个简单的示例:

$(window).bind('mousemove', function() {
    if (elementBeingHoveredOver.attr('id') != 'foo') {
        // ... (Do some cool stuff here) ...
        $(window).unbind('mousemove');
    }
});

我知道,我知道,看起来最好将 mouseentermouseleave 事件处理程序绑定到 #foo 元素并这样做,但是鼠标经常移动得太快而无法注册mouseleave 事件,所以我想尝试这种方式。

关于如何确定elementBeingHoveredOver的任何想法?

【问题讨论】:

    标签: jquery hover mousemove mouseout mouseleave


    【解决方案1】:

    试试这个

    $(window).bind('mousemove', function(e) {
        if ($(e.target).attr('id') != 'foo') {
            // ... (Do some cool stuff here) ...
            $(window).unbind('mousemove');
        }
    });
    

    【讨论】:

      【解决方案2】:

      虽然我仍然建议您绑定到页面上每个元素的鼠标移动事件,但这里有一种通过鼠标位置查找元素的方法:

      当您绑定到文档的鼠标移动事件时,您可以使用pageXpageY 获取光标位置:

      $(document).mousemove(function(e){
          alert(e.pageX);
          alert(e.pageY);
      });
      

      然后通过使用.offset(),您可以获得页面上的元素位置:

      function elementBeingHoveredOver(mouseX, mouseY) {
      
          $('*').each(function() {
              var x = $(this).offset().left;
              var y = $(this).offset().top;
              var width = $(this).width();
              var height = $(this).height();
      
              if (x <= mouseX && y <= mouseY && (x + width) >= mouseX && (y + height) >= mouseY) {
                  return $(this);
              }
          });
      
          return null;    
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-03
        • 2019-12-18
        • 1970-01-01
        • 2011-10-10
        • 2019-12-22
        • 2013-07-10
        相关资源
        最近更新 更多