Jquery:如何在不重复代码的情况下对两组持续时间不同的数字进行动画处理



我的目标是使用不同的持续时间值对两组数字进行动画处理,而无需重复代码。我怎样才能做到这一点?Jquery:

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

和 HTML:

    <div class="counter"><p>2017</p></div>
    <div class="counter"><p>1971</p></div>

我可以通过更改数字"1971"的类名来实现这一点,但随后我将有重复的代码......有人可以给我一个提示吗?

另一个稍微不同的解决方案是将数据标签分配给计数器并以这种方式控制时间。

<div class="counter" data-time="3000"><p>1971</p></div>
<div class="counter" data-time="4000"><p>2017</p></div>


然后在现有函数中将持续时间值替换为对数据标记值的调用。
$('.counter').each(function () {
  var $this = $(this);
  var duration = $(this).data('time');
  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
    duration: duration,
    easing: 'swing',
    step: function () {
      $this.text(Math.ceil(this.Counter));
    }
  });      
});

这是您的一个工作示例。

获取您拥有的代码,将其放入接受参数的函数中。

在下面的例子中,我让函数接受一个sel(css 选择器)和一个duration值。 您还可以根据需要添加其他值。

为了简单起见,我还在您的 html 中添加了类,以便我们可以分别处理每个类。

// Call the animation on the first item with a 1 second duration
animateNumber('.first-counter', 1000);
// Call the animation on the second item with a 5 second duration
animateNumber('.second-counter', 5000);
/**
 * Animate a numeric increment
 * 
 * @param {string} sel - the CSS selector of the element to animate
 * @param {int} duration - the number of milliseconds
 */
function animateNumber(sel, duration) {
    $(sel).each(function() {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: duration,
        easing: 'swing',
        step: function() {
          $this.text(Math.ceil(this.Counter));
        }
      });
    });
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="counter first-counter">
  <p>2017</p>
</div>
<div class="counter second-counter">
  <p>1971</p>
</div>

最新更新