Animate counter when in viewport

前端 未结 3 1627
逝去的感伤
逝去的感伤 2020-12-09 17:26

I have a counter which animates to a final number which is defined in the HTML. However I would like this animation to happen once it\'s in the viewport.

I have a fi

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 17:43

    This solves it if you don't mind change of code. jsfiddle

        var $findme = $('#numbers');
    var exec = false;
    function Scrolled() {
      $findme.each(function() {
        var $section = $(this),
          findmeOffset = $section.offset(),
          findmeTop = findmeOffset.top,
          findmeBottom = $section.height() + findmeTop,
          scrollTop = $(document).scrollTop(),
          visibleBottom = window.innerHeight,
          prevVisible = $section.prop('_visible');
    
        if ((findmeTop > scrollTop + visibleBottom) ||
          findmeBottom < scrollTop) {
          visible = false;
        } else visible = true;
    
        if (!prevVisible && visible) {
        	if(!exec){
                  $('.fig-number').each(function() {
              $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
              }, {
                duration: 1000,
    
                step: function(now) {
                  $(this).text(Math.ceil(now));
                  exec = true;
                }
              });
            });
          }
        }
        $section.prop('_visible', visible);
      });
    
    }
    
    function Setup() {
      var $top = $('#top'),
        $bottom = $('#bottom');
    
      $top.height(500);
      $bottom.height(500);
    
      $(window).scroll(function() {
        Scrolled();
      });
    }
    $(document).ready(function() {
      Setup();
    });
    html,
    body {
      height: 100%;
    }
    
    #upper-push {
      height: 100%;
      width: 100%;
      display: block;
      background: red;
      color: white;
    }
    
    
    Scroll down
    25 78

提交回复
热议问题