我想在元素到达视区的可见区域时启动动画。我找到了一个有助于启动动画的解决方案,但是当用户继续滚动时它就会停止。(见
Multiple viewport checks per page
)
我需要动画开始,而不是停止滚动。
jQuery(function($) {
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
function Utils() {}
Utils.prototype = {
constructor: Utils,
isElementInView: function(element, fullyInView) {
var pageTop = $(window).scrollTop();
var pageBottom = pageTop + $(window).height();
var elementTop = $(element).offset().top;
var elementBottom = elementTop + $(element).height();
if (fullyInView === true) {
return ((pageTop < elementTop) && (pageBottom > elementBottom));
} else {
return ((elementTop <= pageBottom) && (elementBottom >= pageTop));
}
}
};
var Utils = new Utils();
function checkForVisible() {
$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');
var isElementInView = Utils.isElementInView($this, false);
if (isElementInView) {
$({
countNum: $this.text()
}).animate({
countNum: countTo
}, {
duration: 2000,
easing: 'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
}
});
}
});
};
var ticking = false;
window.addEventListener('scroll', function(e) {
if (!ticking) {
window.requestAnimationFrame(function() {
checkForVisible();
ticking = false;
});
ticking = true;
}
});
});
下面是滚动问题的一个示例:
https://codepen.io/cray_code/pen/ywBEzX