jQuery重复循环数组来更改标记属性

时间:2012-02-20 18:17:16

标签: javascript jquery jquery-plugins slider

我正在创建一个简单的滑块,它可以通过更改src标记的img属性和锚标记的属性来实现。这是我到目前为止所提出的:

(function($){
    var slides = [
        'http://placehold.it/801x350',
        'http://placehold.it/802x350',
        'http://placehold.it/803x350'
    ],
    titles = [
        'Title 1',
        'Title 2',
        'Title 3'
    ],
    links =  [
        'http://test1.com',
        'http://test2.com',
        'http://test3.com'
    ],
    image = $('#stretch-img'),
    anchor = $('.featured-title>h2>a');

    var interval = setInterval(function() {
        image.attr('src', slides[0]);
        anchor.attr('href', links[0]);
        anchor.html(titles[0]);
    }, 3000);
})(jQuery);

我希望间隔能够通过简单的淡入淡出效果连续循环遍历数组。什么是最好的方式来做到这一点或任何方式来做到这一点,因为我没有。

谢谢!

我感谢所有的帮助。

1 个答案:

答案 0 :(得分:2)

要遍历数组,您可以设置current-position-variable和保存数组长度的变量:

var current = 0,
    length  = slides.length,
    interval = setInterval(function() {
        image.attr('src', slides[current]);
        anchor.attr('href', links[current]).html(titles[current]);

        current++;
        if (current >= length) {
            current = 0;
        }
    }, 3000);

然后褪色你可以淡出,更改源,然后淡入淡出:

        image.fadeOut(500, function () {
            image.attr('src', slides[current]).fadeIn(500);
            anchor.attr('href', links[current]).html(titles[current]);

            current++;
            if (current >= length) {
                current = 0;
            }
        });

这可能导致在fadeIn(500)启动时图像没有被完全加载,可以通过使用附加到load元素的image事件的事件处理程序来修复:

var image = $('#stretch-img').on('load', function () {
    image.fadeIn(500);
});

然后您可以从间隔函数中删除fadeIn(500),因为它会在图像加载时触发。只要图像源发生变化并且新源完成加载,就会触发load事件。

请注意,.on()是jQuery 1.7中的新增内容,在这种情况下与.bind()相同。