简体   繁体   English

使用 jQuery setTimeout 更改类以在多个元素上设置时间量

[英]use jQuery setTimeout to change classes for set amount of time on multiple elements

I'm trying to have a blurred effect on words when the mouse hovers over them.当鼠标悬停在单词上时,我试图对单词产生模糊效果。 I would like the words to be blurred for a second or so and then return to standard words in the order that they were hovered on.我希望单词模糊一秒钟左右,然后按照它们悬停的顺序返回标准单词。

I've almost got it working, except only the last word hovered on returns to its initial state.我几乎让它工作了,除了最后一个字悬停在返回到它的初始 state 上。 The other words stay blurred.其他词保持模糊。 Does anyone have any suggestions?有没有人有什么建议? See my jsfiddle: http://jsfiddle.net/rrosegregoryy/tavh892w/见我的jsfiddle: http://jsfiddle.net/rrosegregoryy/tavh892w/

And the code I've tried that's not giving me the desired result:而且我尝试过的代码并没有给我想要的结果:

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

I'm quite new to javascript so I'm a little stuck!我对 javascript 很陌生,所以我有点卡住了!

The issue is because you're only using a single setTimeout() reference.问题是因为您只使用了一个setTimeout()引用。 As soon as you hover over the next word the previous timeout is cleared.只要您 hover 超过下一个字,就会清除先前的超时。

To fix this you need to use multiple timeouts, one per word.要解决此问题,您需要使用多个超时,每个单词一个。 You can place them in to the data() of the element to retain a reference to them:您可以将它们放在元素的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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM