jQuery 如果鼠标悬停超过 2 秒然后显示其他不?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11263636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:24:51  来源:igfitidea点击:

If mouse over for over 2 seconds then show else don't?

jqueryhtmlcsstimerslidedown

提问by user1266515

Here is a jQuery slide function I have applied to a div on hover in order to slide a button down.

这是我在悬停时应用于 div 以便向下滑动按钮的 jQuery 滑动功能。

It works fine except that now everytime someone moves in and out of it, it keeps bobbing up and down.

它工作正常,只是现在每次有人进出它时,它都会上下摆动。

I figured if I put a one or two second delay timer on it it would make more sense.

我想如果我在上面放一个一两秒的延迟计时器会更有意义。

How would I modify the function to run the slide down only if the user is on the div for over a second or two?

仅当用户在 div 上超过一两秒时,我将如何修改函数以运行幻灯片?

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>
<script type="text/javascript">

$("#NewsStrip").hover(
function () {
    $("#SeeAllEvents").slideDown('slow');    },
function () {
    $("#SeeAllEvents").slideUp('slow');
});

</script>

回答by Jon

You need to set a timer on mouseover and clear it either when the slide is activated or on mouseout, whichever occurs first:

您需要在鼠标悬停时设置一个计时器,并在幻灯片被激活或鼠标移开时清除它,以先发生者为准:

var timeoutId;
$("#NewsStrip").hover(function() {
    if (!timeoutId) {
        timeoutId = window.setTimeout(function() {
            timeoutId = null; // EDIT: added this line
            $("#SeeAllEvents").slideDown('slow');
       }, 2000);
    }
},
function () {
    if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
    }
    else {
       $("#SeeAllEvents").slideUp('slow');
    }
});

See it in action.

看到它在行动。

回答by xdazz

var time_id;

$("#NewsStrip").hover(
function () {
    if (time_id) {
        clearTimeout(time_id);
    } 
    time_id = setTimeout(function () {
        $("#SeeAllEvents").stop(true, true).slideDown('slow');
    }, 2000);
}, function () {
    if (time_id) {
        clearTimeout(time_id);
    } 
    time_id = setTimeout(function () {
        $("#SeeAllEvents").stop(true, true).slideUp('slow');
    }, 2000);
});