jQuery 动画数字计数器从零到值

问题描述 投票:0回答:13

我创建了一个脚本来将数字从零动画化到其值。

工作

jQuery

$({ Counter: 0 }).animate({
  Counter: $('.Single').text()
}, {
  duration: 1000,
  easing: 'swing',
  step: function() {
    $('.Single').text(Math.ceil(this.Counter));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="Single">150</span>


不工作

我现在想在页面上为每个匹配的类运行脚本几次。

以下是我正在尝试但到目前为止尚未成功的方法:

HTML

<span class="Count">200</span>
<span class="Count">55</span>

JQUERY

$('.Count').each(function () {
  jQuery({ Counter: 0 }).animate({ Counter: $(this).text() }, {
    duration: 1000,
    easing: 'swing',
    step: function () {
      $(this).text(Math.ceil(this.Counter));
    }
  });
});
javascript jquery html animation each
13个回答
100
投票

您的

this
并不引用步骤回调中的元素,而是希望在函数的开头保留对它的引用(在我的示例中包含在
$this
中):

$('.Count').each(function () {
  var $this = $(this);
  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
    duration: 1000,
    easing: 'swing',
    step: function () {
      $this.text(Math.ceil(this.Counter));
    }
  });
});

更新:如果您想显示小数,则可以使用

Math.ceil
将值四舍五入到 2 位小数,而不是使用
value.toFixed(2)
对值进行四舍五入:

step: function () {
  $this.text(this.Counter.toFixed(2));
}

22
投票
步骤回调中的

this
不是元素而是传递给animate()的对象

$('.Count').each(function (_, self) {
    jQuery({
        Counter: 0
    }).animate({
        Counter: $(self).text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            $(self).text(Math.ceil(this.Counter));
        }
    });
});

执行此操作并保留对

this
的引用的另一种方法是

$('.Count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 1000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

小提琴


16
投票

重要:这似乎是一个很小的差异,但您确实应该使用数据属性来保存要计数的原始数字。更改原始数字可能会产生意想不到的后果。例如,每次元素进入屏幕时我都会运行此动画。但如果元素进入、退出,然后在第一个动画结束之前再次进入屏幕,它将计数到错误的数字。

HTML:

<p class="count" data-value="200" >200</p>
<p class="count" data-value="70" >70</p>
<p class="count" data-value="32" >32</p>

JQuery:

$('.count').each(function () {
    $(this).prop('Counter', 0).animate({
            Counter: $(this).data('value')
        }, {
        duration: 1000,
        easing: 'swing',
        step: function (now) {                      
            $(this).text(this.Counter.toFixed(2));
        }
    });
});

5
投票

代码的作用是,数字 8000 从 0 计数到 8000。问题是,它被放置在相当长的页面的中间,一旦用户向下滚动并实际看到数字,动画就已经开始了。吃饭。我想在计数器出现在视口中时触发它。

JS:

$('.count').each(function () {
                $(this).prop('Counter',0).animate({
                        Counter: $(this).text()
                }, {
                        duration: 4000,
                        easing: 'swing',
                        step: function (now) {
                                $(this).text(Math.ceil(now));
                        }
                });
            });

和 HTML:

 <span class="count">8000</span>

3
投票

这是我的解决方案 当元素显示到视口中时,它也正在工作


您可以通过单击 jfiddle

查看正在运行的代码
var counterTeaserL = $('.go-counterTeaser');
var winHeight = $(window).height();
if (counterTeaserL.length) {
    var firEvent = false,
        objectPosTop = $('.go-counterTeaser').offset().top;

        //when element shows at bottom
        var elementViewInBottom = objectPosTop - winHeight;
    $(window).on('scroll', function() {
        var currentPosition = $(document).scrollTop();
        //when element position starting in viewport
      if (currentPosition > elementViewInBottom && firEvent === false) {
        firEvent = true;
        animationCounter();
      }   
    });
}

//counter function will animate by using external js also add seprator "."
 function animationCounter(){
        $('.numberBlock h2').each(function () {
            var comma_separator_number_step =           $.animateNumber.numberStepFactories.separator('.');
            var counterValv = $(this).text();
            $(this).animateNumber(
                {
                  number: counterValv,
                  numberStep: comma_separator_number_step
                }
            );
        });
    }


https://jsfiddle.net/uosahmed/frLoxm34/9/

3
投票

如果你想根据它是 int 还是 float 来处理

$(".display-counter").each(function () {
    $(this)
      .prop("Counter", 0)
      .animate(
        {
          Counter: $(this).text()
        },
        {
          duration: 4000,
          easing: "swing",
          step: function (now, tween) {
            // Check added for decimal number
            if(parseInt(tween.end) == parseFloat(tween.end)){
              $(this).text(Math.ceil(now));
            } else{
              $(this).text(now.toFixed(2));
            }
          },
        }
      );
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="display-counter">123</p>
<p class="display-counter">125.3</p>


1
投票

您可以在

.each()
中获取元素本身,尝试这个而不是使用
this

$('.Count').each(function (index, value) {
    jQuery({ Counter: 0 }).animate({ Counter: value.text() }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            value.text(Math.ceil(this.Counter));
        }
    });
});

1
投票

这对我有用

HTML 代码

<span class="number-count">841</span>

jQuery 代码

$('.number-count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });

1
投票

您可以使用 jQuery 中的 animate 函数来实现。

$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
    duration: 8000,
    easing: 'linear',
    step: function () {
        $('.yourelement').html(Math.floor(this.countNum));
    },
    complete: function () {
        $('.code').html(this.countNum);
        //alert('finished');
   }
});

演示


0
投票

这对我有用

$('.Count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

0
投票

这对我来说是工作!

<script type="text/javascript">
$(document).ready(function(){
        countnumber(0,40,"stat1",50);
        function countnumber(start,end,idtarget,duration){
            cc=setInterval(function(){
                if(start==end)
                {
                    $("#"+idtarget).html(start);
                    clearInterval(cc);
                }
                else
                {
                   $("#"+idtarget).html(start);
                   start++;
                }
            },duration);
        }
    });
</script>
<span id="span1"></span>

0
投票
    $({ Counter: 0 }).animate({
      Counter: $('.Single').text()
    }, {
      duration: 1000,
      easing: 'swing',
      step: function() {
        $('.Single').text(Math.ceil(this.Counter));
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span class="Single">150</span>

0
投票

我正在将我的石头添加到大厦中!以下代码使用交叉点观察器触发计数器:

    $({ Counter: 0 }).animate({
      Counter: $('.Single').text()
    }, {
      duration: 1000,
      easing: 'swing',
      step: function() {
        $('.Single').text(Math.ceil(this.Counter));
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span class="Single">150</span>

© www.soinside.com 2019 - 2024. All rights reserved.