首页 > 解决方案 > JQuery如何在每次显示时为里程碑计数器设置动画

问题描述

正如标题所说,基本上我如何在每次显示时重复计数器动画。

到目前为止,我设法使里程碑编号具有动画效果,并且我找到了当目标元素在视口中时执行某些操作的代码。

但是,我不知道如何使它们都起作用。我试图将动画代码粘贴到 //do something 部分,但它不起作用。

这是我到目前为止的进展

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

jQuery(document).ready(function( $ ){
(function($) {
    var $animation_elements = $('.count'),
        $window = $(window);
 
    function check_if_in_view() {
        var window_height = $window.height(),
            window_top_position = $window.scrollTop(),
            window_bottom_position = (window_top_position + window_height);
 
        $animation_elements.each(function() {
            var $element = $(this),
                element_height = $element.outerHeight(),
                element_top_position = $element.offset().top,
                element_bottom_position = (element_top_position + element_height);
 
            //check to see if this element is within viewport
            if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {
                $element.addClass('et-animated'); //test with adding new class is working
            } else {
                $element.removeClass('et-animated'); //test with removing the class is working
            }
        });
    }
 
    $window.on('scroll resize', check_if_in_view);
})(jQuery);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div style="margin-bottom: 500px;">Scroll down to see the counter</div>

<div><span class="count">123000</span></div>
<div><span class="count">3500000</span></div>
<div><span class="count">50000</span></div>

标签: jqueryhtml

解决方案


下面的代码按您的要求运行。

它检查.count元素在页面加载时以及滚动后是否可见。它使用该类.nonVisible来帮助确定计数器是刚刚进入还是离开它,这样我们就可以适当地停止动画。

如果您在元素滚动出视图时不停止动画,则动画将继续运行,如果元素重新进入视图,它将不会再次开始,而是继续原始动画。

类似地,在计数器移出视线后将其文本设置为“0”意味着用户在计数器重新启动之前不会短暂看到前一个图形。

下面的代码已完全注释。


演示

// Add event on document ready
$(document).ready(function() {



  // Add event on document scroll
  $(window).scroll(function() {

    // Cycle through each counter
    $(".count").each(function() {

      // Check if counter is visible
      if ($(this).isOnScreen()) {

        // Start counter
        startCounter($(this));

      } else {

        // Check if it has only just become non-visible
        if ($(this).hasClass("notVisible") == false) {

          // Stop animation
          $(this).stop();

          // Add nonVisible class
          $(this).addClass("notVisible");
          
          // This stops the user very briefly seeing the previous number before the counter restarts
          $(this).text("0");

        }

      }
    });
  });
});


// Check if an element is on screen
// Thanks to Adjit - taken from the url below
// Reference : https://stackoverflow.com/questions/23222131/jquery-fire-action-when-element-is-in-view#answer-23222523
$.fn.isOnScreen = function() {

  var win = $(window);

  var viewport = {
    top: win.scrollTop(),
    left: win.scrollLeft()
  };

  viewport.right = viewport.left + win.width();
  viewport.bottom = viewport.top + win.height();

  var bounds = this.offset();
  bounds.right = bounds.left + this.outerWidth();
  bounds.bottom = bounds.top + this.outerHeight();

  return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));


};


//Run counter, separate function so we can call it from multiple places
function startCounter(counterElement) {

  // Check if it has only just become visible on this scroll
  if (counterElement.hasClass("notVisible")) {

    // Remove notVisible class
    counterElement.removeClass("notVisible");

    // Run your counter animation
    counterElement.prop('Counter', 0).animate({
      Counter: counterElement.attr("counter-lim")
    }, {
      duration: 4000,
      easing: 'swing',
      step: function(now) {
        counterElement.text(Math.ceil(now).toLocaleString());
      }
    });
  }
}


// On page load check if counter is visible
$('.count').each(function() {

  // Add notVisible class to all counters
  // It is removed within startCounter()
  $(this).addClass("notVisible");

  // Check if element is visible on page load
  if ($(this).isOnScreen() === true) {

    // If visible, start counter
    startCounter($(this));

  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div><span class="count" counter-lim="123000"></span></div>

<div style="margin-bottom: 500px;">Scroll down to see the counter</div>

<div><span class="count" counter-lim="123000"></span></div>
<div><span class="count" counter-lim="350000"></span></div>
<div><span class="count" counter-lim="50000"></span></div>


推荐阅读