简体   繁体   English

.animate()不会将元素样式更改回原始样式

[英].animate() will not change element styles back to original

I have written a function that simulates the update of a 'live' element. 我编写了一个函数来模拟“实时”元素的更新。 It picks an element at random and then animates it using .animate() and .effect() from the jQuery UI library. 它随机选择一个元素,然后使用jQuery UI库中的.animate().effect()对其进行动画处理。 However, once the animations have finished the element should return back to it's original color, but for some reason this doesn't happen. 但是,一旦动画完成,元素应返回到其原始颜色,但是由于某种原因,这种情况不会发生。 Find below the code and JSFiddle . 在下面的代码和JSFiddle中找到

var decider = Math.round(Math.random() * 6) + 1
var original = $('.tile:nth-child(' + decider + ')').css('background-color');
var a = $('.tile:nth-child(' + decider + ')');

$(a).animate({
    backgroundColor: 'green'
}).effect('shake', {
    distance: 5,
    times: 1
}, 1000).animate({
    backgroundColor: original
});
$(a).hover(function () {
    $(this).animate({
        backgroundColor: original
    }).finish();
});

replace your run function with the given one. 用给定的函数替换运行函数。

function run(){
    var decider = Math.round(Math.random() * 6) + 1
    var original = $('.tile:nth-child(' + decider + ')').css('background-color');
    var a = $('.tile:nth-child(' + decider + ')');

    $(a).animate({
        backgroundColor: 'green'
    }).effect('shake', {
        distance: 5,
        times: 1
    }, 1000).animate({
        backgroundColor: original
    });
    $(a).hover(function () {
        $(this).animate({
            backgroundColor: original
        }).finish();
        clearInterval(myVar);
    });
    var myVar = setTimeout(run, 1000);
}

this must help you :) 这必须帮助您:)

You have a timing issue there. 您那里有计时问题。 Every time you are running run() , it checks for the original color depending on the DOM. 每次运行run() ,它都会根据DOM检查original颜色。 But what if the DOM color is still green when checked, and not original ? 但是,如果检查时DOM颜色仍然是绿色而不是original颜色,该怎么办?

It's a good practice to use animate() callback function for stuff that happens after animation finishes. 对于动画结束后发生的事情,最好使用animate()回调函数。 That way you know that animation has finished and at it's right state, instead of using a arbitrary time value. 这样,您就知道动画已经完成并且处于正确的状态,而不是使用任意时间值。

function run(){
    var decider = Math.round(Math.random() * 6) + 1
    var original = $('.tile:nth-child(' + decider + ')').css('background-color');
    var a = $('.tile:nth-child(' + decider + ')');

    $(a).animate({
        backgroundColor: 'green'
    }).effect('shake', {
        distance: 5,
        times: 1
    }, 1000, function() {    
        // first animation finish, start second animation
        $(this).animate({
            backgroundColor: original
        }, 1000, function () {
           // second animation finish, re-run
           run();
        });
    });
}

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

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