1

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

这是一个快速示例:

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

mouseenter我知道,我知道,将一个和mouseleave事件处理程序绑定到元素并这样做似乎会更好#foo,但是鼠标经常移动得太快而无法注册mouseleave事件,所以我想尝试这种方式。

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

4

2 回答 2

3

试试这个

$(window).bind('mousemove', function(e) {
    if ($(e.target).attr('id') != 'foo') {
        // ... (Do some cool stuff here) ...
        $(window).unbind('mousemove');
    }
});
于 2011-12-12T20:33:52.607 回答
2

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

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

$(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;    
}
于 2011-12-12T20:34:26.707 回答