滚动时可以看到jQuery动画

时间:2016-09-09 23:04:20

标签: javascript jquery

计数动画本身可以工作,但最初不在视口中。

目标是在进入视图时启动计数动画,但下面的代码不起作用。有什么建议吗?

$(window).on('scroll', function() {
  var $elem = $('.showchart');
  var $window = $(window);

  var docViewTop = $window.scrollTop();
  var docViewBottom = docViewTop + $window.height();
  var elemTop = $elem.offset().top;
  var elemBottom = elemTop + $elem.height();
  if (elemBottom < docViewBottom) {
   $('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 2000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
}); 
  }
});  
  

1 个答案:

答案 0 :(得分:2)

https://jsfiddle.net/k65ro3po/2/ 看到这个小提琴进行比较。我注意到你从本教程中取了一个例子:https://codepen.io/shivasurya/pen/FatiB,所以我也抓了它并编辑它以便进行滚动。

您的代码存在一些问题: 首先,滚动发生在document,而不是window。其次,你的计算似乎是错误的。此外,如果你没有停止触发,动画将循环并循环,导致重大错误。

我这样修好了:

HTML:

<div class="filler">
  Scroll down!
</div>
<div id="talkbubble"><span class="count">78</span></div>

CSS

.count {
  line-height: 100px;
  color: white;
  margin-left: 30px;
  font-size: 25px;
}

#talkbubble {
  width: 120px;
  height: 80px;
  background: red;
  position: relative;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
  float: left;
  margin: 20px;
}

#talkbubble:before {
  content: "";
  position: absolute;
  right: 100%;
  top: 26px;
  width: 0;
  height: 0;
  border-top: 13px solid transparent;
  border-right: 26px solid red;
  border-bottom: 13px solid transparent;
}

.filler {
  height: 800px;
  width: 100%;
}

使用Javascript:

$(function() {
  var $elem = $('#talkbubble');
  var windowHeight = $(window).height();
  var elemTop = $elem.offset().top - windowHeight;
  var counted = false;
  $(document).on("scroll", function() {
    var scrollY = $(this).scrollTop();
    if (scrollY > elemTop && !counted) {
      //there is no more need to waste CPU power on triggering this after it's done its job
      $(document).off("scroll");
      //set counted to true so it doesn't trigger again. This is a back-up of the above
      counted = true;
      $('.count').each(function() {
        $(this).prop('Counter', 0).animate({
          Counter: $(this).text()
        }, {
          duration: 2000,
          easing: 'swing',
          step: function(now) {
            $(this).text(Math.ceil(now));
          }
        });
      });
    }
  });

});

- 您应该避免重新设置在on.scroll()等函数中始终相同的变量。它将重做数百次计算,只需要完成一次。