gol*_*nge 4 html javascript jquery css3 css-animations
我有通过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 */
Run Code Online (Sandbox Code Playgroud)
加载页面时,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');
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
现在这是问题所在.只检查每个第二个元素是否可见,如下所示:
但它应该是这样的:
仅当页面向下滚动时,其余元素才会生成动画,其中:
$window.scroll( function()
{
animate();
});
Run Code Online (Sandbox Code Playgroud)
如何遍历此场景中的每个元素?
编辑:
记下@TJ Crowder评论我用@charlietfl建议的过滤函数修改了animate函数:
$('.animate').filter( function( idx ) {
if( isElementVisible($(this)) )
{
$(this).addClass( $(this).data('effect') );
$(this).removeClass('animate');
}
});
Run Code Online (Sandbox Code Playgroud)
它工作得很好:)谢谢你们.
那里有几个问题:
您正在修改$toAnimate正在迭代的set(),并且您正在使用不断增加的索引从该集合中检索项目.所以很自然地,如果你删除一个,从那时起你的索引就会被取消.
splice不是官方的jQuery方法.它没有记录,可能随时消失.(jQuery对象不是数组;它们只是数组.)
据我所知,jQuery让没有保证什么each,如果你在你遍历集合添加或删除条目会做(不像JavaScript的forEach).
因为你有splice和迭代保证forEach,你可以$toAnimate使用.get以下方法创建一个实际的数组:
var $toAnimate = $('.animate').get();
// ---------------------------^^^^^^
Run Code Online (Sandbox Code Playgroud)
...然后:
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');
}
});
}
Run Code Online (Sandbox Code Playgroud)