Function for mouse near an element in jQuery

倾然丶 夕夏残阳落幕 提交于 2019-12-18 19:03:51

问题


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.

This is my code.

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

How can I do this with jQuery?


回答1:


This works. The first parameter can be any jQuery object. The second parameter is the nearness to the object, in this case 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 );

};


来源:https://stackoverflow.com/questions/7911604/function-for-mouse-near-an-element-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!