[英]How to add a delay to CSS Vertical Dropdown Menu
I am needing to add a delay to the mouseover event of my dropdown menu so that if someone mouses over the menu going to another link on page the menu will not drop down instantly. 我需要为下拉菜单的mouseover事件添加一个延迟,以便如果有人将鼠标悬停在菜单上,而该鼠标转到页面上的另一个链接,则菜单不会立即下拉。 Thanks for your help.
谢谢你的帮助。
http://jsfiddle.net/cgagliardi/NPVVQ/ http://jsfiddle.net/cgagliardi/NPVVQ/
You can add a setTimeout()
to delay the show()
, and on hover out clear the timeout so that if the user moves the mouse out before the delay is up it will be cancelled. 您可以添加
setTimeout()
来延迟show()
,并在悬停时清除超时,这样,如果用户在延迟结束前将鼠标移出,它将被取消。 And you can encapsulate that in your own jQuery plugin: 您可以将其封装在自己的jQuery插件中:
jQuery.fn.hoverWithDelay = function(inCallback,outCallback,delay) {
this.each(function(i,el) {
var timer;
$(this).hover(function(){
timer = setTimeout(function(){
timer = null;
inCallback.call(el);
}, delay);
},function() {
if (timer) {
clearTimeout(timer);
timer = null;
} else
outCallback.call(el);
});
});
};
Which you can use like this: 您可以这样使用:
$('ul.top-level li').hoverWithDelay(function() {
$(this).find('ul').show();
}, function() {
$(this).find('ul').fadeOut('fast', closeMenuIfOut);
}, 500);
I cobbled that plugin together in a hurry so I'm sure it could be improved, but it seems to work in this updated version of your demo: http://jsfiddle.net/NPVVQ/3/ 我急忙将这个插件拼凑在一起,所以我敢肯定它可以加以改进,但是它似乎可以在您的演示的更新版本中使用: http : //jsfiddle.net/NPVVQ/3/
As far as explaining how my code works: the .each()
loops through all the elements in the jQuery object that the function is called on. 至于解释我的代码是如何工作的:
.each()
循环调用该函数的jQuery对象中的所有元素。 For each element a hover handler is created that uses setTimeout()
to delay calling the callback function provided - if the mouseleave occurs before the time is up this timeout is cleared so that the inCallback
is not called. 对于每个元素,将创建一个悬停处理程序,该悬停处理程序使用
setTimeout()
延迟调用提供的回调函数-如果在时间到了之前发生了inCallback
, inCallback
清除此超时,以便不调用inCallback
。 The .call()
method is used on inCallback
and outCallback
to set the right value for this
. 所述
.call()
方法被用在inCallback
和outCallback
设定为正确值的this
。
You can use CSS3 Animation or Transition. 您可以使用CSS3动画或过渡。
http://www.css3maker.com/css3-animation.html http://www.css3maker.com/css3-animation.html
http://www.css3maker.com/css3-transition.html http://www.css3maker.com/css3-transition.html
Or you can handle timeouts in Javascript, I think a easy way is to attach a setTimeout
before show();
或者您可以使用Javascript处理超时,我认为一种简单的方法是在
show();
之前附加一个setTimeout
show();
and use clearTimeout
on mouseleave event 并在mouseleave事件上使用
clearTimeout
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.