如何为jquery鼠标悬停添加延迟

How to add delay to jquery mouseover?

本文关键字:悬停 添加 延迟 鼠标 jquery      更新时间:2023-09-26

我在一个页面上有一堆图像,我使用以下命令来触发事件:

$('.img').on('mouseover', function() {
 //do something
});

是否有一些方法可以添加延迟,这样如果用户悬停1秒,那么它确实"//做一些事情"或实际上触发"mouseover"事件?

您可以使用setTimeout

var delay=1000, setTimeoutConst;
$('.img').on('hover', function() {
  setTimeoutConst = setTimeout(function() {
    // do something
  }, delay);
}, function() {
  clearTimeout(setTimeoutConst);
});

如果用户离开得太快,您可以使用setTimeoutclearTimeout来做到这一点:

var timer;
var delay = 1000;
$('#element').hover(function() {
    // on mouse in, start a timeout
    timer = setTimeout(function() {
        // do your stuff here
    }, delay);
}, function() {
    // on mouse out, cancel the timer
    clearTimeout(timer);
});

使用计时器并在鼠标离开时清除它,如果他们在1000ms内离开

var timer;
$('.img').on({
    'mouseover': function () {
        timer = setTimeout(function () {
            // do stuff
        }, 1000);
    },
    'mouseout' : function () {
        clearTimeout(timer);
    }
});

我也在寻找这样的东西,但也有二次延迟。我选择了这里的一个答案,并对其进行了扩展

这个例子在鼠标悬停X秒后显示一个div,并在鼠标悬停X秒后隐藏它。但如果将鼠标悬停在显示的div上,则会禁用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
.foo{
  position:absolute; display:none; padding:30px;
  border:1px solid black; background-color:white;
}
</style>
<h3 class="hello">
  <a href="#">Hello, hover over me
    <span class="foo">foo text</span>
  </a>
</h3>

<script type="text/javascript">
var delay = 1500, setTimeoutConst, 
    delay2 = 500, setTimeoutConst2;
$(".hello").mouseover(function(){
  setTimeoutConst = setTimeout(function(){
    $('.foo').show();
  },delay);
}).mouseout(function(){
  clearTimeout(setTimeoutConst );
  setTimeoutConst2 = setTimeout(function(){
    var isHover = $('.hello').is(":hover");
    if(isHover !== true){
      $('.foo').hide();
    }
  },delay2);
});
</script>
工作示例

你可以像这样使用jquery .Delay(未测试):

$("#test").hover(
    function() {
        $(this).delay(800).fadeIn();
    }
);
http://api.jquery.com/delay/