【问题标题】:jQuery animation not working (number countdown/count-up)jQuery 动画不起作用(数字倒计时/向上计数)
【发布时间】:2014-02-17 23:26:15
【问题描述】:

我的脚本如下所示:

function powerClick(level, cost, user) {
    clicks = Number(clicks) - cost;
    addBPS();
}
function addBPS() {     
    var from = {property: $('#current').text()};
    var to = {property: Number(clicks)};
    jQuery(from).animate(to, {
        duration: 1000,
        step: function() {
            $('#current').text((Math.floor(this.property)));
        }
    });
}

第一个函数在单击按钮时运行,并调整clicks 的值。然后它运行函数addBPS(在它的正下方)。

然而,函数addBPS 并没有完全倒计时到存储在变量clicks 中的数字。很多时候,函数powerClick 将变量clicks 设置为0。但是,当函数addBPS 运行时,计数器不会一直下​​降到零。

这是为什么?

【问题讨论】:

  • 您是否已将控制台日志插入到代码中,并仔细检查所有变量是否符合您的预期?
  • @A2345sooted 我使用了警告框,我确信变量是我想要的。

标签: javascript jquery debugging animation counter


【解决方案1】:

我在这里看到的可能问题:

  1. 可能是因为 clicks 没有全局定义?所以每次它结束运行第一个函数时,值都会被销毁。
  2. 尝试将 this.property 替换为 to.property 或 from.property?
  3. 我建议使用不太通用的变量名称,例如“to”或“from”。有一天,您可能会发现自己不假思索地使用保留关键字。 (发生在我身上)

    var clicks;
    
    function powerClick(level, cost, user) {
        clicks = Number(clicks) - cost;
        addBPS();
    }
    function addBPS() {     
        var data_before = {property: $('#current').text()};
        var data_after = {property: Number(clicks)};
        jQuery(from).animate(to, {
            duration: 1000,
            step: function() {
                $('#current').text((Math.floor(data_after.property)));
            }
        });
    }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多