我目前正在研究Counter
显示我主页的一些统计信息。这是我正在使用的脚本:
$('.count-1, .count-2, .count-3, .count-4').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
现在我只想在计数器出现在屏幕上时运行这个动画......所以我得到了这个脚本:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.class').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
// run this if .class gets in viewpoint
} else {
// run this else
}
});
});
});
所以我把这两个脚本放在一起:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.count-1, .count-2, .count-3, .count-4').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
} else {
}
});
});
});
现在,如果我在我的页面上向下滚动,计数器会在它进入屏幕时开始运行(这正是我想要的)但是当计数器完成时,计数器开始倒数直到.count-1
, .count-2
... 在1
。即使我再次上下滚动......计数器仍然停留在1
。有时对1
a 的更改2
或3
但很快又会下降到 a 1
。
这是片段:
$(document).ready(function () {
var windowHeight = $(window).height(),
gridTop = windowHeight * -10,
gridBottom = windowHeight * .9;
$(window).on('scroll', function () {
$('.count-1, .count-2, .count-3, .count-4').each(function () {
var thisTop = $(this).offset().top - $(window).scrollTop();
if (thisTop > gridTop && (thisTop + $(this).height()) < gridBottom) {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 5000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
} else {
}
});
});
});
/* just for some scrolling */
#container {
margin-top: 1000px;
margin-bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll down!</p>
<div id="container">
<div class="count-1">200</div>
<div class="count-2">100</div>
<div class="count-3">50</div>
<div class="count-4">4</div>
</div>
错误在哪里?