1

有没有办法随机化这个 jquery 幻灯片中的图像,这样每次页面刷新时它都不会以相同的图像开始?

这是HTML:

<div id="slideshow">

<img src="http://image.jpg" alt="image 1" class="active">
<img src="http://image.jpg" alt="image 2" >
<img src="http://image.jpg" alt="image 3" >

</div>

这是脚本:

function slideSwitch() {
var $active = $('#slideshow IMG.active');

if ( $active.length == 0 ) $active = $('#slideshow IMG:last');

var $next =  $active.next().length ? $active.next()
    : $('#slideshow IMG:first');

$active.addClass('last-active');

$next.css({opacity: 0.0})
    .addClass('active')
    .animate({opacity: 1.0}, 6000, function() {
        $active.removeClass('active last-active');

    });
}

$(function() {
setInterval( "slideSwitch()", 8000 );
});

谢谢!!!!

4

2 回答 2

0

首先按编号定义所有具有类的图像。比如说,“图像 1”、“图像 2”、“图像 3”等。不要为任何图像定义活动类。然后使用此代码随机给任何图像“活动”类。

$(document).ready(function() {
     var random = 1 + Math.floor(Math.random() * 3);
     $('.image ' + random).addClass('active');
})

如果有 'n' 个图像,请使用 var random = 1 + Math.floor(Math.random() * n);

于 2013-01-21T10:56:05.873 回答
0

您可以在页面加载时为您的图像标签随机分配active类,例如:

$(document).ready(function() {
  $("#slideshow img").removeClass("active");
  randomDiv = $("#slideshow img").get().sort(function(){ 
     return Math.round(Math.random())-0.5
  }).slice(0,1);
  $(randomDiv).addClass("active");
});

这样每次新的 img 标签获取活动类并将从该 img 标签开始

于 2013-01-21T10:51:48.213 回答