我有一系列要通过CSS3进行动画处理的元素,如下所示:
.anim-slide-left {
animation: anim-slide-left 0.8s ease forwards;
-webkit-animation: anim-slide-left 0.8s ease forwards;
}
@-webkit-keyframes anim-slide-left {
0% {
transform: translateX(-500px);
-webkit-transform: translateX(-500px);
opacity: 0;
}
100% {
transform: translateX(0);
-webkit-transform: translateX(0);
opacity: 1;
}
}
/* there are more, but very similar */
当页面加载时,js应该只为具有特殊类‘animate’的可见元素设置动画:
$(function() {
var $window = $(window);
var $toAnimate = $('.animate');
animate();
// check if element is on the viewport
function isElementVisible(elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = elementToBeChecked.offset().top;
return ((TopElement <= BotView) && (TopElement >= TopView));
}
// add css animation class
function animate()
{
$toAnimate.each(function(i, el)
{
var $el = $toAnimate.eq(i);
if ($el.length && isElementVisible($el))
{
// remove already visible elements
$toAnimate.splice(i, 1);
// setting up animation effect
$el.addClass( $el.data('effect') );
$el.removeClass('animate');
}
});
}
});
现在问题来了。每隔一段时间才检查一次元素是否可见,如下所示:
但是它应该是这样的:
其余的元素只有在页面向下滚动时才会显示动画,其中包含:
$window.scroll( function()
{
animate();
});
如何遍历这个场景中的每个元素?
编辑:
注意到@T.J. Crowder的评论,我用@charlietfl建议的过滤函数修改了动画函数:
$('.animate').filter( function( idx ) {
if( isElementVisible($(this)) )
{
$(this).addClass( $(this).data('effect') );
$(this).removeClass('animate');
}
});
它工作得很好:)谢谢你们。
发布于 2015-08-02 20:20:40
这里有几个问题:
$toAnimate
),并且您正在使用不断增加的索引从该集合中检索项。因此,很自然地,如果您删除一个,从这一点开始,您的索引将是off.splice
不是一个正式的jQuery方法。它没有记录在案,随时可能消失。(据我所知,jQuery对象不是数组;它们只是array-like.)each
决定(不像JavaScript的just因为您有splice
和来自forEach
的迭代保证,所以可以使用.get
使$toAnimate
成为实际的数组
var $toAnimate = $('.animate').get();
// ---------------------------^^^^^^
然后...and:
function animate()
{
$toAnimate.forEach(function(el)
{
var $el = $(el);
if (isElementVisible($el))
{
// remove already visible elements
$toAnimate.splice(i, 1);
// setting up animation effect
if( $el.data('effect') == 'anim-bar' ) animateBar($el);
else $el.addClass( $el.data('effect') );
$el.removeClass('animate');
}
});
}
发布于 2015-08-02 20:21:43
您正在从要迭代的数组中删除项,因此下一项将替换当前项。当您移动到下一项时,将跳过一项。
如果从末尾开始循环数组,则删除项不会影响循环后面的项:
function animate()
{
for (var i = $toAnimate.length - 1; i >= 0; i--)
{
var $el = $toAnimate.eq(i);
if ($el.length && isElementVisible($el))
{
// remove already visible elements
$toAnimate.splice(i, 1);
// setting up animation effect
if( $el.data('effect') == 'anim-bar' ) animateBar($el);
else $el.addClass( $el.data('effect') );
$el.removeClass('animate');
}
});
}
https://stackoverflow.com/questions/31771773
复制相似问题