2011-11-17 98 views
0

我的网站上有浮动框。我在mousenter上显示它并隐藏onmouseleave。就像这样:jquery:在效果之前添加延迟

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

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

当我进行过 “盒子” 快速移动鼠标它显示了。 如何不在这种情况下显示它? 谢谢。

+0

您可以发布hideBox而showBox藏汉?也许做一个jsfiddle? – BjarkeCK

回答

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(); 
} 
+0

谢谢!有用。 – Nick

1

缠上你的setTimeout函数调用()

$(box).mouseenter(function(evt) { setTimeout("showBox()",1000);}); 

,其中1000为1秒。 (1000 milisecond = 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 
} 
+0

当您快速完成鼠标移动时,它仅在1秒后显示。 这您将需要。但你也需要清除你的mouseleave的超时时间。对? – BjarkeCK

+0

是这样的吗? –

1

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

这是合租容易写类似:

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

此事件触发之前增加500ms的延迟。它处理了事件触发多次时必须设置/取消/重置定时器的所有工作。

(它也支持方便的节流选项更复杂的情况,你可以在链接阅读)

+0

你仍然需要取消事件 –

+0

是的,这是事实,当然可以在'mouseleave'事件中完成。该插件与其他答案中发布的代码几乎完全相同。我发现把所有的管道都隐藏起来很方便。特别是如果你在一页上有几个这样的东西。 – njr101