Show popup if the mouse is hovered over an element for a period of time

孤街浪徒 提交于 2019-12-09 17:58:49

问题


I'm wondering how to show a popup/tipbox when a mouse has been hovered over an element for a period of time, e.g. pseudo code:

if mouseover
    if hovered for more than 2 seconds
       --> show popup/tipbox
    else
       ---> cancel mouseover
else if mouseout
    --> reset timer/cancel mouseover

I've done this so far, but it doesn't work effectively, if I hover and move the mouse quickly, it will still show the popup/tipbox.

$('a[rel=tip]').live('mouseover mouseout', function(e)
{
    if(e.type == 'mouseover')
    {
        var mouseTime = setTimeout(function()
        {
            $('.tipbox').slideDown('fast');
        }, 1000);
    }
    else if(e.type == 'mouseout')
    {
        if(mouseTime)
        {
            cancelTimeout(mouseTime);
            mouseTime = null;
            $('.tipbox').slideUp('fast');   
        }
    }
});

EDIT: Bounty added.


回答1:


This seems to work for me:

http://jsfiddle.net/eydMC/3/

HTML

<span id="someelem">Hover me for 2 seconds!</span>

JS

var tooltipTimeout;

$("#someelem").hover(function()
                    {tooltipTimeout = setTimeout(showTooltip, 2000);}, 
                    hideTooltip);

function showTooltip()
    {
    var tooltip = $("<div id='tooltip' class='tooltip'>I'm the tooltip!</div>");
    tooltip.appendTo($("#someelem"));
    }

function hideTooltip()
    {
    clearTimeout(tooltipTimeout);
    $("#tooltip").fadeOut().remove();
    }

CSS

#someelem
    {
    cursor: pointer;
    }

.tooltip
    {
    display: block;
    position: absolute;
    background-color: rgb(130, 150, 200);
    padding: 5px;
    }



回答2:


Try this:

function show_tipbox (thelink,tipbox) { 
    var timer; 
    timer = setTimeout(function(){
        $(tipbox).stop(true, true).fadeIn('normal');
    }, 300); 
    $(thelink).mouseout(function(){ clearTimeout(timer); });
}

function hide_tipbox (tipbox) {
    $(tipbox).stop(true, true).fadeOut('normal');
}

And the html code should be:

<a href="#" id="thelink" onmouseover="show_tipbox('#thelink','#tipbox');">The link</a>
<div id="tipbox" onmouseout="hide_tipbox('#tipbox');">Tipbox Content</div>



回答3:


You could try This plugin - it's written by one of the authors of a very good jQuery book, so ought to be good. The demos look promising.



来源:https://stackoverflow.com/questions/4944550/show-popup-if-the-mouse-is-hovered-over-an-element-for-a-period-of-time

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