开发者

Prevent a hover event from happening if the mouse isn't focused for over a set time?

I am using this code for tooltips, a simple function I wrote to display title tags a little nicer on a webpage;

function tooltip(target_items, name){

 $(target_items).each(function(i){

$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
var my_tooltip = $("#"+name+i);

$(this).removeAttr("title").mouseover(function(){
        my_tooltip.css({display:"none"}).stop(true, tr开发者_如何学编程ue).slideDown(225);
}).mousemove(function(kmouse){
        my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
}).mouseout(function(){
        my_tooltip.css({display:"none"});                 
});
 });

 }

I want it so that the whole thing will only trigger if the mouse is over it for a set amount of time, say 1000. If the mouse leaves the trigger area before that time I want it so the event never happens at all.


Probably you need to set timeout and clear it if 1 second not finished:

function tooltip(target_items, name) {

$(target_items).each(function (i) {

    $("body").append("<div class='" + name + "' id='" + name + i + "'><p>" + $(this).attr('title') + "</p></div>");
    var my_tooltip = $("#" + name + i);
    var myTooltipTimer;
    var delay = 1000;

    $(this).removeAttr("title").mouseover(function () {
        myTooltipTimeout = window.setTimeout(function () {
            my_tooltip.css({ display: "none" }).stop(true, true).slideDown(225);
            myTooltipTimeout = null;
        }, delay);
    }).mousemove(function (kmouse) {
        my_tooltip.css({ left: kmouse.pageX + 15, top: kmouse.pageY + 15 });
    }).mouseout(function () {
        if (myTooltipTimer != null)
            window.clearTimeout(myTooltipTimer);
        else {
            my_tooltip.css({ display: "none" });
        }
    });
});

maybe using jQuery exists more clear solution


Have a look at the jQuery HoverIntent plugin: http://cherne.net/brian/resources/jquery.hoverIntent.html

Since you are implementing tooltips on your own, have a look at http://craigsworks.com/projects/qtip2/ - it might be what you need without requiring lots of custom code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜