如何将setTimeout()函数与jquery stop()函数结合起来?

时间:2014-11-17 08:55:34

标签: javascript jquery

我知道使用stop()函数强制排队操作。例如,

$(seletor).stop().fadeIn();

当用户触发mouseenter或mouseouter事件时,它可以防止多个淡入淡出效果。
现在我想使用带有setTimeout()函数的stop()函数或其他东西来防止多个模拟排队效果。 这是HTML:

<div class="container">
    <div class="inner"></div>
    <div class="inner2"></div>
</div>

CSS:

.container{
    width: 200px;
    height: 400px;
    overflow: scroll;
    background-color: #ccc;
    position: relative;
}

.inner, .inner2{
    width: 10px;
    height: 500px;
    background-color: red;
}

.inner{
    display: none;
}

.inner2{
    position: absolute;
    left: 10px;
    top: 0;
    background-color: green; 
}

JS:

$(function(){
    //$(".container").stop().on("scroll", function(){
    $(".container").on("scroll", function(){
        $(".inner").stop().fadeIn();
        setTimeout(function(){
            $(".inner").stop().fadeOut();
        }, 1000);
    });
});

jsfiddle ftw :) 我的目的是在用户滚动div时触发setTimeout函数隐藏红色部分。但正如我之前所说,我不知道如何将stop()和setTimeout()函数组合在一起。当多次滚动时,红色部分会以序列多次淡化和淡出。
请帮助我,非常感谢!

1 个答案:

答案 0 :(得分:0)

如果您希望它不断淡入/淡出,您应该链接.fadeIn().fadeOut()

这样的事情可能更像你正在寻找的......

$(function(){
    var ref = null;
    $(".container").on("scroll", function(){
        clearTimeout(ref);
        $(".inner").stop().fadeIn();
        ref = setTimeout(function(){
            $(".inner").stop().fadeOut();
        }, 1000);
    });
});

这将继续处理动画的fadin / out事件,然后当你停止滚动一秒钟时,停止/淡出将保持不变。

相关问题