如何在下面的代码中添加setTimeout来延迟渐变动画

How do I add setTimeout to delay the fading animation in the following code?

本文关键字:setTimeout 延迟 渐变 动画 添加 在下面 代码      更新时间:2023-09-26

我正在使用以下内容来淡入和淡出hover:上的元素

$(".hidden").hover(function() {
  $(this).animate({
    opacity: 1
  });
}, function() {
  $(this).animate({
    opacity: 0
  });
});

我想在不透明度1和不透明度0之间添加一个延迟(等待片刻,然后淡出元素)。

我怎样才能做到这一点?

$(".hidden").hover(function() {
  $(this).animate({
    opacity: 1
  });
}, function() {
  var _this = $(this);
  setTimeout(function (){
    _this.animate({
      opacity:0
    });
  },1000)
});

Yuu可以使用.delay()函数http://api.jquery.com/delay/.

$(".hidden").hover(function() {
  $(this).delay(1000).animate({
    opacity: 1
  });
}, function() {
  $(this).delay(1000).animate({
    opacity: 0
  });
});

http://jsfiddle.net/gk14nqrx/

这将在淡出前延迟1秒。您需要存储对$(this)的引用,因为在setTimeout内部,this不再是DOM元素。

$(".hidden").hover(function() {
  $(this).animate({
    opacity: 1
  });
}, function() {
  var that = $(this);
  setTimeout(function() {
      $(this).animate({
        opacity: 0
      });
  }, 1000);
});