javascript - 使用 jQuery setTimeout 在多个元素上更改类的设定时间量

标签 javascript jquery

当鼠标悬停在单词上时,我试图对单词产生模糊效果。我希望单词模糊一秒钟左右,然后按照悬停的顺序恢复为标准单词。

我几乎已经开始工作了,除了最后一个字悬停在返回到它的初始状态。其他词保持模糊。有没有人有什么建议?查看我的 jsfiddle:http://jsfiddle.net/rrosegregoryy/tavh892w/

我试过的代码没有给我想要的结果:

var hoverTimeout;
$('span').hover(function() {
    clearTimeout(hoverTimeout);
    $(this).addClass('hovered');
}, function() {
    var $self = $(this);
    hoverTimeout = setTimeout(function() {
        $self.removeClass('hovered');
    }, 1000);
});

我是 javascript 的新手,所以有点卡住了!

最佳答案

问题是因为您只使用了一个 setTimeout() 引用。只要您将鼠标悬停在下一个单词上,就会清除之前的超时。

要解决此问题,您需要使用多个超时,每个单词一个。您可以将它们放入元素的 data() 以保留对它们的引用:

(function(count) {
  'use strict';
  (function wrap(el) {
    $(el).filter(':not(script)').contents().each(function() {
      // Node.* won't work in IE < 9, use `1`
      if (this.nodeType === Node.ELEMENT_NODE) {
        wrap(this);
        // and `3` respectively
      } else if (this.nodeType === Node.TEXT_NODE && !this.nodeValue.match(/^\s+$/)) {
        $(this).replaceWith($.map(this.nodeValue.split(/(\S+)/), function(w) {
          return w.match(/^\s*$/) ? document.createTextNode(w) : $('<span>', {
            id: count = count + 1,
            text: w
          }).get();
        }));
      }
    });
  }('body'));
}(0));

$('span').hover(function() {
  let $self = $(this).addClass('hovered');
  clearTimeout($self.data('timeout'));
}, function() {
  var $self = $(this);
  $self.data('timeout', setTimeout(function() {
    $self.removeClass('hovered');
  }, 1000));
});
p {
  font-size: 26px;
}

.hovered {
  filter: blur(3px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div>
  <p>hello my name is rose how are you </p>
</div>

关于javascript - 使用 jQuery setTimeout 在多个元素上更改类的设定时间量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65918678/

相关文章:

javascript - 遍历 jquery 中的多个下拉列表

javascript - 通过多次使用 switchClass 使类相互淡化

javascript - 数组重新/赋值引用更改

javascript - 如何使用 jquery 将 javascript 对象传递给另一个函数

javascript - AngularJS 起源 http ://localhost:8080 is not allowed by Access-Control-Allow-Origin

javascript - FormioJS : How to return values from data. 自定义选择?

javascript - 在 Apache Cordova 中实现 CSS sidenav

javascript - 动态添加 AdWords 再营销列表标记

Javascript 多维数组 : Add Values

javascript - 错误的 <li> 标签行为