【问题标题】:How to display running counter in Javascript?如何在 Javascript 中显示正在运行的计数器?
【发布时间】:2010-02-23 14:44:24
【问题描述】:

我有一个包含数值的表格单元格。

在更改值时,我想创建一个计数器以 100 步向上(或向下)移动直到达到新值的效果。

我尝试过类似以下的方法(在 jQuery 的帮助下):

函数更新(元素,新值) { var oldValue = parseFloat($(element).text()); var diff = (newValue - oldValue) / 100; for (var i = 0; i

但是,在脚本完成之前,Javascript 似乎不会刷新显示 - 因此没有效果。

如何确保在每一步都显示中间值?

【问题讨论】:

    标签: javascript jquery effects


    【解决方案1】:

    这样的东西是非常面向 jQuery 的:

    jQuery.fn.extend({
      animateCount : function (from, to, time) {
        var steps = 1,
            self = this,
            counter;
    
        if (from - to > 0) {
          steps = -1;
        };
    
        from -= steps;
    
        function step() {
          self.text(from += steps);
    
          if ((steps < 0 && to >= from) || (steps > 0 && from >= to)) {
            clearInterval(counter);
          };
        };
    
        counter = setInterval(step, time || 100);
      }
    });
    

    现在只需使用:

    $('#selector').animateCount(1,100);
    

    从 1 到 100,每 100 毫秒递增一次。间隔是可选的第三个参数。

    【讨论】:

      【解决方案2】:

      JavaScript 和 DOM 共享同一个线程,因此当前正在执行脚本时无法刷新显示。它必须等到线程空闲。您只能通过 setTimeoutsetInterval 调用来实现您想要做的事情,使用计时器而不是循环来增加每个步骤。

      【讨论】:

        【解决方案3】:

        不确定 JQuery 方面,但这里有一个快速示例页面:

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
            <head>
                <title>test</title>
                <script type="text/javascript">
                    var t, max, i;
        
                    function Increase(amount) {
                        max = amount;
                        i = parseInt(document.getElementById("count").value);
                        t = setInterval("SetIncrease()", 10);
                    }
        
                    function SetIncrease() {
                        document.getElementById("count").value = ++i;
                        if(i == max) {
                            clearTimeout(t);
                        }
                    }
                </script>
            </head>
            <body>
                <input id="count" type="text" value="1"/>
                <input type="button" value="Up" onclick="Increase(100)"/>
            </body>
        </html>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-11
          • 2017-10-01
          • 2017-06-18
          • 2010-09-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多