如何在CSS垂直下拉菜单中添加延迟 [英] How to add a delay to CSS Vertical Dropdown Menu

查看:709
本文介绍了如何在CSS垂直下拉菜单中添加延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为下拉菜单的mouseover事件添加一个延迟,以便如果有人将鼠标悬停在菜单上,而该鼠标转到页面上的另一个链接,则菜单不会立即下拉. 感谢您的帮助.

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. Thanks for your help.

http://jsfiddle.net/cgagliardi/NPVVQ/

推荐答案

您可以添加setTimeout()来延迟show(),并在悬停时清除超时,以便用户在延迟之前将鼠标移出到了,它将被取消.您可以将其封装在自己的jQuery插件中:

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. And you can encapsulate that in your own jQuery plugin:

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);
        });
    });
};

您可以这样使用:

$('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/

就解释我的代码如何工作而言:.each()遍历调用该函数的jQuery对象中的所有元素.对于每个元素,将创建一个悬停处理程序,该悬停处理程序使用setTimeout()延迟调用提供的回调函数-如果在时间到时发生鼠标离开,则将清除此超时,以便不调用inCallback.在inCallbackoutCallback上使用.call()方法为this设置正确的值.

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. 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. The .call() method is used on inCallback and outCallback to set the right value for this.

这篇关于如何在CSS垂直下拉菜单中添加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆