如何为jquery mouseover添加延迟?

时间:2013-03-22 17:01:32

标签: javascript jquery

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

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

});

是否有某种方法可以添加延迟,如果用户徘徊1秒钟,那么它会“执行某些操作”或实际触发“鼠标悬停”事件?

5 个答案:

答案 0 :(得分:35)

您可以使用setTimeout

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

答案 1 :(得分:22)

如果用户过早离开,您可以使用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);
});

答案 2 :(得分:4)

使用计时器并在鼠标停留时清除它们,并在1000毫秒内离开

var timer;

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

答案 3 :(得分:4)

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

此示例显示鼠标悬停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>

Working example

答案 4 :(得分:2)

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

$("#test").hover(
    function() {
        $(this).delay(800).fadeIn();
    }
);

http://api.jquery.com/delay/

相关问题