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

当用户滚动时jQuery动画停止

  •  0
  • Cray  · 技术社区  · 5 年前

    我在我的网站上使用了多个数字元素,这些元素在到达视口的可见区域后开始计数。

    在用户手动滚动页面之前,该部分仍然有效。如果用户向上或向下滚动,动画将停止一秒钟,并在用户不再滚动时重复。它看起来很笨重。

    如果我试图用小提琴来复制这个问题,同样的代码总是可以在没有“结巴”的情况下工作吗?

    jQuery(function($) {
      $(function($, win) {
        $.fn.inViewport = function(cb) {
          return this.each(function(i, el) {
            function visPx() {
              var H = $(this).height(),
                r = el.getBoundingClientRect(),
                t = r.top,
                b = r.bottom;
              return cb.call(el, Math.max(0, t > 0 ? H - t : (b < H ? b : H)));
            }
            visPx();
            $(win).on("resize scroll", visPx);
          });
        };
      }(jQuery, window));
    
      $(".fig-number").inViewport(function(px) {
        // if px>0 (entered V.port) and
        // if prop initNumAnim flag is not yet set = Animate numbers
        if (px > 0 && !this.initNumAnim) {
          this.initNumAnim = true; // Set flag to true to prevent re-running the same animation
    
          $(this).prop('Counter', 0).animate({
            Counter: $(this).text()
          }, {
            duration: 10000,
            step: function(now) {
              $(this).text(Math.ceil(now));
            }
          });
        }
      });
    });
    html,
    body {
      height: 100%;
    }
    
    .spacer {
      height: 100%;
      width: 100%;
      display: block;
      background: red;
      color: white;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="spacer">
      scroll down
    </div>
    <div class="number-box">
      <h1 class="fig-number">1000</h1>
      <h1 class="fig-number">1500</h1>
    </div>
    <div class="spacer">
      scroll down
    </div>
    <div class="number-box">
      <h1 class="fig-number">2000</h1>
      <h1 class="fig-number">2500</h1>
    </div>
    <div class="spacer">
      scroll down
    </div>
    <div class="number-box">
      <h1 class="fig-number">3000</h1>
      <h1 class="fig-number">3500</h1>
    </div>

    工作小提琴(相同代码): https://jsfiddle.net/JSCray/r7g0vn93/3/

    0 回复  |  直到 5 年前