代码之家  ›  专栏  ›  技术社区  ›  iceiceicy

jquery每次显示时如何动画里程碑计数器

  •  0
  • iceiceicy  · 技术社区  · 7 年前

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

    到目前为止,我设法使里程碑编号成为动画,并且找到了在目标元素位于视图端口时执行某些操作的代码。

    但是,我不知道如何让这两个都起作用。我试图将动画代码粘贴到//做某件事的部分,但它不起作用。

    这是我目前的进展

    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>
    1 回复  |  直到 7 年前
        1
  •  1
  •   Oliver Trampleasure    7 年前

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

    它检查 .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>