jQuery中元素附近元素的功能

Din*_*nga 13 html javascript jquery javascript-events

我希望在鼠标靠近桌面元素时跟踪并显示工具提示.它适用于该mouseenter事件,但我希望mouseenter在它接近之前显示工具提示.另外,我希望在mouseout距离桌头一定距离后删除工具提示.

这是我的代码.

$('thead').mouseenter(showtooltip);
$('thead').mouseout(removetooltip);
Run Code Online (Sandbox Code Playgroud)

我怎么能用jQuery做到这一点?

Thi*_*iff 30

这有效.第一个参数可以是任何jQuery对象.在这种情况下,第二个参数是对象的接近度20px.

演示:http://jsfiddle.net/ThinkingStiff/Lpg8x/

脚本:

$( 'body' ).mousemove( function( event ) {

    if( isNear( $( 'thead' ), 20, event ) ) {
        //show your tooltip here
    } else {
        //hide it here
    };

});           

function isNear( element, distance, event ) {

    var left = element.offset().left - distance,
        top = element.offset().top - distance,
        right = left + element.width() + 2*distance,
        bottom = top + element.height() + 2*distance,
        x = event.pageX,
        y = event.pageY;

    return ( x > left && x < right && y > top && y < bottom );

};
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案似乎相当CPU重 (3认同)