javascript - 使用 jquery 循环遍历 div 中的子项并制作动画

标签 javascript jquery html css

我想使用 jquery 创建一个连续滚动的图像 slider 。这是我所能得到的。我不太明白如何传递函数参数,尤其是当我使用 this 时。这个想法是启动一个动画并将图像从 div 外部移动到 View 之外的另一侧,然后重置其位置。后面的图像将在其之前的图像通过起点后立即开始其动画,依此类推。 (我计算出速度是 250 像素/秒,因此当前元素的宽度除以 250 应该给我应该等待启动下一个动画的时间,我认为......)

<div class="slideshow" style="position: absolute; top: 220px;left: 50%; margin-left: -700px;height: 600px; width: 1400px; z-index: 2;">
     <img src="img2.jpg" id="img2" class="slideshowImages">
     <img src="img3.jpg" id="img3" class="slideshowImages">
     <img src="img4.jpg" id="img4" class="slideshowImages"> 
     <img src="img1.jpg" id="img1" class="slideshowImages">
</div>

    </body>
    <script>
        $(document).ready(setTimeout(function() {
            var InfiniteRotator =
            {
                init: function(ident, time)
                {
                    $(ident).animate({"margin-left": "-=2500"},{ duration:10000,easing: 'linear',queue:false, complete:function(){
                    $(ident).css("margin-left", "1400px"); 
                    } 
                      // Animation complete.
                    }).delay(time);
                }

            }
            var time = 0;
            $('div.slideshow').each(function(){

                InfiniteRotator.init(this, time);
                time = $(this).width()/250;
            });
        }, 3000));

    </script>

最佳答案

$('div.slideshow') 引用一个元素(包含图像的 div),因此对其调用 each 不会像您的图像那样迭代您的图像代码似乎假设。

$('div.slideshow img').each(function(){
    InfiniteRotator.init(this, time);
    time = $(this).width()/250;
});

在这个修改后的版本中,this 指的是当前图像元素(jQuery 提供的一个很好的快捷方式)。此代码执行相同的操作:

$('div.slideshow img').each(function(index, element){
    InfiniteRotator.init(element, time);
    time = $(this).width()/250;
});

如果您想“像 jQuery 一样”并允许 InfiniteRotator 使用 this 访问当前图像,您可以使用 callapply 而不是直接调用 init 方法并将元素作为上下文传递(this 在被调用函数中引用的内容):

$('div.slideshow img').each(function(index, element){
    InfiniteRotator.init.call(element, element, time);
    time = $(this).width()/250;
});

var InfiniteRotator =
{
   init: function(ident, time)
   {
      $(this).animate({"margin-left": "-=2500"}, { 
        duration:10000,
        easing: 'linear',
        queue:false, 
        complete:function(){
            $(this).css("margin-left", "1400px"); 
        } 
       }).delay(time);
    }
}

关于javascript - 使用 jquery 循环遍历 div 中的子项并制作动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20580056/

相关文章:

javascript - 使用 Javascript 将多个输入字段合并为一个输入字段?

javascript - 带有固定顶栏的移动滑动菜单

javascript - 在 Javascript 中包含模块的正确方法是什么?

javascript - ember.js 链接到帮助程序中的“this”

javascript - 如何在 Chart.js 中放置静态点并制作垂直线

javascript - 在 Firefox 中 scrollTop 关闭 1 个像素

javascript - 通过for循环发送信息

Jquery fadeIn() 不透明度 :0 or visibility:hidden

javascript - 使用 Class 声明原型(prototype)默认值的 ecmascript 6 语法

javascript - 在不使用 split 方法的情况下找到字符串中最长的单词