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

标签 javascript jquery html css animation

我编写了一个模拟“实时”元素更新的函数。它随机选择一个元素,然后使用 jQuery UI 库中的 .animate().effect() 对其进行动画处理。然而,一旦动画结束,元素应该返回到它的原始颜色,但由于某种原因,这并没有发生。在下面找到代码和 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();
});

最佳答案

你那里有时间问题。 每次运行 run() 时,它都会根据 DOM 检查 original 颜色。但是,如果 DOM 颜色在检查时仍然是绿色,而不是原始怎么办?

对于动画结束后发生的事情,使用 animate() 回调函数是一个很好的做法。这样您就知道动画已经完成并处于正确的状态,而不是使用任意时间值。

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();
        });
    });
}

关于javascript - .animate() 不会将元素样式改回原始样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33954655/

相关文章:

jquery - 如果选中则更改选择值不起作用

javascript - 将标签替换为span标签

javascript - 使用 javaScript 创建表格并为其添加样式

html - Margin : auto-ed elements = to padding left of 100%-width overflow item 的左边距

javascript - 显示数据后合并边框

javascript - 使用 HTML/JavaScript 检测本地文件拖放

javascript - 如何从 html 更改 angularjs 变量

javascript - 从ajax动态加载导航中删除Attr(href)

javascript - Crossfilter 对过滤后的维度进行分组

javascript - 使用 SeedStack 中的 RequireJS 防止 Javascript 文件出现浏览器缓存问题