【发布时间】:2021-06-03 19:47:35
【问题描述】:
我正在尝试制作一个滚动 jQuery 序列,当它在视图中时,它会一个接一个地为元素设置动画。 Here is my CodePen 这是代码:
$(document).ready( function() {
var $window = $(window);
var $animatedItem = $('.has-animation');
$animatedItem.css({
"visibility": "hidden"
});
// Check if in view.
function runAnimation() {
var windowTop = $window.scrollTop();
var windowHeight = $window.height();
var windowWidth = $window.width();
var windowBottom = (windowTop + windowHeight + windowWidth);
$animatedItem.each( function() {
var $element = $(this);
var elementTop = $element.offset().top;
var elementHeight = $element.outerHeight();
var elementWidth = $element.outerWidth();
var elementBottom = (elementTop + elementHeight + elementWidth);
if (windowTop > elementTop - windowHeight / 1.2) {
// Check to see if this current container is within viewport.
if ((elementBottom >= windowTop) && (elementTop <= windowBottom)) {
$element.each( function(i) {
// Stagger the elements into view.
setTimeout( function() {
$element.eq(i).removeClass('has-animation').css({
"visibility": "visible"
});
$element.eq(i).addClass('animated');
$element.eq(i).addClass('in-view');
}, 330 * (i+1));
});
}
}
});
}
$window.on('scroll resize', runAnimation);
$window.trigger('scroll');
});
我有它,所以当元素滚动到视图中时,类“.has-animation”被替换为“.animated”和“.in-view”。元素样式“可见性”也由隐藏变为可见。
目前,当元素到达视点时,它们都同时动画化,而不是每个元素一个接一个地动画化。
我已尝试在此代码中替换 $element:
$element.each( function(i) {
// Stagger the elements into view.
setTimeout( function() {
$element.eq(i).removeClass('has-animation').css({
"visibility": "visible"
});
$element.eq(i).addClass('animated');
$element.eq(i).addClass('in-view');
}, 330 * (i+1));
});
使用 $animatedItem 所以它看起来像这样:
$animatedItem.each( function(i) {
// Stagger the elements into view.
setTimeout( function() {
$animatedItem.eq(i).removeClass('has-animation').css({
"visibility": "visible"
});
$animatedItem.eq(i).addClass('animated');
$animatedItem.eq(i).addClass('in-view');
}, 330 * (i+1));
});
而且这段代码($animatedItem 代码)实际上做了我正在寻找的东西,但是,元素在滚动时立即动画,而不是在它们到达视点时加载。这让我相信像这样的函数应该被定向到 $animatedItem 但在我的代码开头附近?
我是 JS/JQuery 的新手(自学),我在弄清楚这一点时遇到了一些麻烦,感谢任何帮助!谢谢大家!
【问题讨论】:
标签: jquery animation jquery-animate settimeout onscroll