jquery:在效果之前添加延迟

时间:2011-11-17 16:52:24

标签: jquery css-float

我的网站上有浮动框。我在mousenter上显示它并隐藏onmouseleave。像这样:

$(box).mouseenter(function(evt) {showBox();});

$(what).parent().mouseleave(function(evt) {hideBox();});

当我执行快速鼠标移动"框时#34;它出现了。 那个案子怎么不显示呢? 感谢。

3 个答案:

答案 0 :(得分:2)

var showTimer;

$( box ).hover( function(){
    // wait .5 sec to show the box
    showTimer = setTimeout( showBox, 500 );

}, function(){
    // wipe timer so that showBox isn't called if < .5 sec
    if( showTimer ){
        clearTimeout( showTimer );
        showTimer = null;
    }

    hideBox();
}

答案 1 :(得分:1)

使用setTimeout()

包裹函数调用
$(box).mouseenter(function(evt) { setTimeout("showBox()",1000);});

其中1000是1秒。 (1000毫秒= 1秒)

编辑:

这可能比我想象的要复杂一点。如果鼠标快速移出,你必须防止它出现。

var t;
$(box).mouseenter(function(evt) { t = setTimeout("showBox()",1000);});
$(box).mouseleave(function(evt) { clearTimeout(t); });
$(what).parent().mouseleave(function(evt) {clearTimeout(t);hideBox();});
function showBox(){
    clearTimeout(t);
    // the rest or your function
}

答案 2 :(得分:1)

我发现bindWithDelay插件对于这些场景非常有用。

很容易写出类似的内容:

$(box).bindWithDelay("mouseenter", function() { ... }, 500);

这会在事件触发前增加500毫秒的延迟。它处理事件多次触发时必须设置/取消/重置计时器的所有管道。

(它还支持一个方便的限制选项,适用于您可以在链接中阅读的更复杂的情况)

相关问题