随机图像幻灯片与jQuery

时间:2013-03-21 05:54:51

标签: jquery html slideshow fadein fadeout

我有这些代码的图片幻灯片: -

Jquery的: -

$(function() {
var current = 0,

    $imgs = jQuery('#header .abc71');
    imgAmount = $imgs.length;

$($imgs.css('position', 'absolute').hide().get(0)).show();


window.setInterval(swapImages, 4000);

function swapImages() {
    var $currentImg = $($imgs[current]);
    if(current == imgAmount-1) current = -1;
    var $nextImg = $($imgs[++current]),
        speed = 1500;
    // animation speed should be the same for both images so we have a smooth change
    $currentImg.fadeOut(speed);
    $nextImg.fadeIn(speed);
    }
});

HTML: -

<div id="header">
   <img class="abc71" src="img1.png"/>
   <img class="abc71" src="img2.png" />
   <img class="abc71" src="img3.png"/>
 </div>

这些脚本运行良好。但我想以随机顺序显示图像。我如何修改我的脚本。或者我应该使用任何其他脚本?请帮助我...谢谢

2 个答案:

答案 0 :(得分:3)

如果随机数大于length,则可以使用random()为图像数组生成随机索引,然后将其设置为图像数组length-1

$(function() {
    var current = 0,      
    $imgs = jQuery('#header .abc71');
    imgAmount = $imgs.length;    
    $($imgs.css('position', 'absolute').hide().get(0)).show();
    window.setInterval(swapImages, 4000);

    function swapImages() {
        current = Math.floor((Math.random()*imgAmount)+1);
    if(current > imgAmount-1) current = imgAmount -2;
    var $currentImg = $($imgs[current]);       
    var $nextImg = $($imgs[current+1]),
        speed = 1500;
    // animation speed should be the same for both images so we have a smooth change
    $currentImg.fadeOut(speed);
    $nextImg.fadeIn(speed);

    }
});

答案 1 :(得分:3)

知道了。我更新了一些代码以使其更清晰。使用有趣的选择器,例如:hidden和:visible。他们真的很棒。

这是小提琴:

JSFiddle

$(function () {
var current = 0,

$imgs = jQuery('#header .abc71');
imgAmount = $imgs.length;

$($imgs.css('position', 'absolute').hide().get(0)).show();


window.setInterval(swapImages, 1000);

function swapImages() {

    var $currentImg = $('.abc71:visible');

    var $nextImg = $('.abc71:hidden').eq(Math.floor(Math.random() * $('.abc71:hidden').length));
        speed = 500;
    // animation speed should be the same for both images so we have a smooth change
    $currentImg.fadeOut(speed);
    $nextImg.fadeIn(speed);
}
});