jQuery中元素附近元素的功能

时间:2022-11-04 17:32:32

I want to track and show a tooltip when the mouse is near a table head element. It works with the mouseenter event, but I want show the tooltip before mouseenter, when it gets near. Also I want remove the tooltip after mouseout some distance from the table head.

我希望在鼠标靠近桌面元素时跟踪并显示工具提示。它适用于mouseenter事件,但是我希望在它接近之前显示mouseenter之前的工具提示。我也想在鼠标离开桌头一段距离后删除工具提示。

This is my code.

这是我的代码。

$('thead').mouseenter(showtooltip);
$('thead').mouseout(removetooltip);

How can I do this with jQuery?

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

1 个解决方案

#1


28  

This works. The first parameter can be any jQuery object. The second parameter is the nearness to the object, in this case 20px.

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

Demo: http://jsfiddle.net/ThinkingStiff/Lpg8x/

Script:

$( '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 );

};

#1


28  

This works. The first parameter can be any jQuery object. The second parameter is the nearness to the object, in this case 20px.

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

Demo: http://jsfiddle.net/ThinkingStiff/Lpg8x/

Script:

$( '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 );

};