gpt4 book ai didi

javascript - 只有第二个元素被迭代

转载 作者:太空狗 更新时间:2023-10-29 12:24:43 28 4
gpt4 key购买 nike

我有要通过 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');
}
});
}
});

问题来了。只有第二个元素被检查为可见,如下所示:

enter image description here

但是应该是这样的:

enter image description here

其余元素仅在页面向下滚动时才会动画,其中:

$window.scroll( function()
{
animate();
});

如何遍历此场景中的每个元素?

编辑:

注意到@T.J. Crowder 评论我用 @charlietfl 建议的过滤器函数修改了动画函数:

$('.animate').filter( function( idx ) {
if( isElementVisible($(this)) )
{
$(this).addClass( $(this).data('effect') );
$(this).removeClass('animate');
}
});

它工作得很好 :) 谢谢你们。

最佳答案

存在的几个问题:

  1. 您正在修改您正在迭代的集合 ($toAnimate),并且您正在使用不断增加的索引从该集合中检索元素。所以很自然地,如果您删除了一个,从那时起您的索引将会关闭。

  2. splice 不是官方的 jQuery 方法。它没有记录在案,随时可能消失。 (jQuery 对象不是数组;它们只是类数组。)

  3. 据我所知,jQuery 使 no guarantees关于如果您在要迭代的集合中添加或删除条目(与 JavaScript 的 forEach 不同)each 会做什么。

因为您有 spliceforEach 的迭代保证,您可以使用 .get 使 $toAnimate 成为一个实际数组:

var $toAnimate = $('.animate').get();
// ---------------------------^^^^^^

...然后:

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');
}
});
}

关于javascript - 只有第二个元素被迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31771773/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com