jQuery计数功能

时间:2017-12-08 16:30:42

标签: javascript jquery

当我到达#counter时,我写了这个来启动计数功能。当我滚动到#counter时,数字从1到600就像它想象的那样。问题是它会回到1.我只想留在600.

$(window).scroll(function() {
  var hT = $('#counter').offset().top,
    hH = $('#counter').outerHeight(),
    wH = $(window).height(),
    wS = $(this).scrollTop();
  console.log((hT - wH), wS);

  if (wS > (hT + hH - wH)) {
    $('.count').each(function() {
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 2000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    });
  }

});
.box {
  height: 900px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div class="box"></div>
  <div id="counter">
  <div><span class="count">600</span></div>
</div>

1 个答案:

答案 0 :(得分:0)

使用.stop() jQuery方法,一旦值为600,就可以停止动画。

&#13;
&#13;
$(window).scroll(function() {
   var hT = $('#counter').offset().top,
   hH = $('#counter').outerHeight(),
   wH = $(window).height(),
   wS = $(this).scrollTop();

if (wS > (hT+hH-wH)) {
	
$('.count').each(function (index, value) {
    $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
	}, {
        duration: 2000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
			if(Math.ceil(now) === 600){
				$(this).stop(true, true);
			}
        }
    });
    });
}

});
&#13;
#counter{
	margin-top: 100vh;
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Counter</title>
</head>
<body>
<p>scroll to view the counter</p>
<div id="counter">
<div><span class="count">600</span></div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
	
</body>
</html>
&#13;
&#13;
&#13;

以上是上述代码段https://jsbin.com/dejeji/edit?html,js,output

的jsbin