如何延迟 jquery 悬停事件

How to delay jquery hover event

本文关键字:jquery 悬停 事件 延迟 何延迟      更新时间:2023-09-26

我有一个带有类别的菜单,当我将鼠标悬停在类别上时,会显示一个下拉菜单(我已经延迟了下拉菜单在 600 毫秒后显示),

我想知道如何将类别上的悬停事件延迟 600 毫秒,使用jquery实现此目的的最佳方法和最简单的方法是什么?

jQuery('div.dropdown').hover(function() {
    jQuery(this).find('.services-shortcut').addClass('active');
    jQuery(this).find('.dropdown-menu').stop(true, true).delay(600).fadeIn(0);
}, function() {
    jQuery(this).find('.services-shortcut').removeClass('active');
    jQuery(this).find('.dropdown-menu').stop(true, true).delay(600).fadeOut(0);
});

我在这里做了一个靴子 http://www.bootply.com/lXioubaMre

您可以使用基本的 CSS 过渡

.services-shortcut {
    transition: all 0s .6s;
}

600ms延迟后立即运行

示例:http://www.bootply.com/xppQzbvQ3P

如果你选择在javascript

中绝对地做这个效果(但我不会这样做,只是为了远离javascript的风格),那么在600ms超时后应用active类,例如

jQuery('div.dropdown').hover(function() {
    var $this = $(this);
    setTimeout(function() {
        $this.find('.services-shortcut').addClass('active');
    }, 600);
    $this.find('.dropdown-menu').stop(true, true).delay(600).fadeIn(0);
}, ...

如果使用此方法,则还应清除间隔onmouseout

您可以使用 hoverIntent jQuery 插件,它根据客户端鼠标移动触发函数。在您的情况下,脚本会很简单,您可以看看这个 Bootply:

function showMenu(e) {
    jQuery(this).find('.services-shortcut').addClass('active');
    jQuery(this).find('.dropdown-menu').show();
};
function hideMenu(e) {
    jQuery(this).find('.services-shortcut').removeClass('active');
    jQuery(this).find('.dropdown-menu').hide();
};
$("div.dropdown").hoverIntent({
    over: showMenu,
    out: hideMenu,
    sensitivity: 3,
    timeout: 800
});
$(".dropdown-menu a").hoverIntent({
    over: function(){
        $(this).addClass('active')
    },
    out: function(){
        $(this).removeClass('active')
    },
    sensitivity: 3
});

我会使用 $.hoverDelay() 插件来做到这一点。它允许您配置"输入"和"输出"事件的延迟,如下所示:

$('div.dropdown').hoverDelay({
  delayIn: 200,
  delayOut:700,
  handlerIn: function($element){
    $element.css({backgroundColor: 'red'});  
  },
  handlerOut: function($element){
    $element.css({backgroundColor: 'auto'});  
  }
});
你可以

简单地使用jQuery.delay()方法

jQuery('div.dropdown').hover(function() {
  alert("Action delayed");
    jQuery(this).find('.services-shortcut').addClass('active');
    jQuery(this).find('.dropdown-menu').stop(true, true).delay(600).fadeIn(0);
}, function() {
    jQuery(this).find('.services-shortcut').removeClass('active');
    jQuery(this).find('.dropdown-menu').stop(true, true).delay(600).fadeOut(0);
}).delay(600);
.dropdown{
  background-color:red;
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="dropdown">
  aaaa
  </div>

这将等待600ms执行您的操作,这就是您所需要的。