javascript - 使用 jQuery setTimeout 在多个元素上更改类以设置时间量
问题描述
当鼠标悬停在单词上时,我试图对单词产生模糊效果。我希望单词模糊一秒钟左右,然后按照它们悬停的顺序返回标准单词。
我几乎让它工作了,除了最后一个字悬停在返回到它的初始状态。其他词保持模糊。有没有人有什么建议?见我的 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 - 如何多次调用javascript
- javascript - Javascript 转换实现,如 css
- flutter - 在颤动中左右移动对象
- javascript - 选择检查主体时如何更新 MongoDB 中的数据
- rest - 一般来说,为用户设置两条 GET 路由(一条用于 ID,一条用于用户名)是否是多余的?
- c# - 在随机行和列中排列对象
- python - 从运行 python 脚本导入变量
- reactjs - 打字稿中的调度类型
- azure-devops - 我有 yaml 管道,它将在 4 个区域中使用 tf 创建我的 az 资源(rg、vnet、aks ..)。使用相同的 piplin 我想在 2 个区域中创建 acr?
- css - 我有一个 CSS,我希望它内联对齐