我有一个简单的计数器,当它在视口中时,我希望它计数到一个设定的数量。
但是,我有两个问题...
函数声明供参考:
function numberCounter() {
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 1500,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});
};
方法1 isInViewport()
:
使用以下代码块,将对div中滚动的每个像素执行该功能。这会导致计数器抖动,除非用户停止滚动,否则计数器不会计数。
$(window).on(' scroll', function() {
if ($('.numberTicker').isInViewport()) {
console.log("test");
numberCounter();
$(window).off('resize scroll');
}
});
方法2 visible()
:
为解决上述问题,我认为检查div是否在视口上可见将执行一次该功能,但是,计数器似乎根本无法正常工作吗?
jQuery(document).ready(function($){
var ticker = $('.numberTicker');
if(ticker.visible(true)) {
numberCounter();
}
});
我要去哪里错了?
完整演示:
function numberCounter() {
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
$({
countNum: $this.text()
}).animate({
countNum: countTo
},
{
duration: 1500,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
});
};
jQuery(document).ready(function($){
var ticker = $('.numberTicker');
if(ticker.visible(true)) {
numberCounter();
}
});
// $(window).on(' scroll', function() {
// if ($('.numberTicker').isInViewport()) {
// console.log("test");
// numberCounter();
// $(window).off('resize scroll');
// }
// });
.spacer {
height: 400px;
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- is visible plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-visible/1.2.0/jquery.visible.min.js"></script>
<div class="spacer">scroll down</div>
<div class="numberTicker">
<h3 class="counter" data-count="50">50</h3>
</div>