为stop().hide()添加延迟



我正在显示/隐藏一个div悬停在另一个div上。

$(".div1, .div2").hover(
function () {
    $(".div2").stop().show('slow');
}, function () {
    $(".div2").stop().hide('slow');
});
https://jsfiddle.net/zvbtL71L/

这很好。然而,div之间有一个小的空间,所以当光标移动到第二个div时,会有一个轻微的跳跃效果,或者如果光标在它们之间的间隙中,它就会消失。

通过在隐藏第二个div中添加延迟来解决这个问题就足够了。我如何为隐藏添加一个短延迟?

Try

jQuery(function($) {
  $('.div1').hover(function() {
    var $target = $('.div2');
    clearTimeout($target.data('hoverTimer'));
    $target.stop().slideDown(500);
  }, function() {
    var $target = $('.div2');
    var timer = setTimeout(function() {
      $target.stop().slideUp();
    }, 200);
    $target.data('hoverTimer', timer);
  });
  $('.div2').hover(function() {
    clearTimeout($(this).data('hoverTimer'));
  }, function() {
    $(this).stop().slideUp();
  });
});
.container {
  position: relative;
}
.div1,
.div2 {
  padding: 20px;
  width: 200px
}
.div1 {
  background: #000;
  color: #fff
}
.div2 {
  background: #eee;
}
.div2 {
  display: none;
  position: absolute;
  top: 70px;
  left: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div class="div1">Hover over me</div>
  <div class="div2">Show hide me</div>
</div>

我发现,为了解决这样的问题,设置计时器等总是变得混乱,需要大量的代码。如果你试图经常做这些事情,你真的应该考虑一个动画库,如GSAP。使用它们的延迟和重写函数,这就变成了小菜一碟:

$(".div1, .div2").hover(
function () {
    tweenMax.to($(".div2"), .5, {display:'block', overwrite:1});
}, function () {
    tweenMax.to($(".div2"), .5, {display:'none', delay:.1});
});

最新更新