【问题标题】:Loop through children in div and animate using jquery循环遍历 div 中的子项并使用 jquery 进行动画处理
【发布时间】:2013-12-14 14:13:16
【问题描述】:

我想使用 jquery 创建一个连续滚动的图像滑块。这是我所能得到的。我不太明白如何传递函数参数,尤其是当我使用this 时。这个想法是启动动画并将图像从 div 外部移动到视图之外的另一侧,然后重新设置其位置。后面的图像将在它之前的图像通过起点时立即开始动画,依此类推。 (我发现速度是 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>

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

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

    【讨论】:

    • 我在修改它时遇到了麻烦,所以它对我有用。索引的目的是什么?
    • Index 是 jQuery 自动传递的,作为当前元素的索引。将其视为for(var i = 0; ..) 循环中的i。我不一定建议你改成这个,只是想帮助你理解this
    猜你喜欢
    • 2012-07-22
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多