是否可以使此代码随机化幻灯片的图像?

Is this possible to make this code randomize the images for the slideshow

本文关键字:图像 幻灯片 随机化 可以使 代码 是否      更新时间:2023-09-26

这里我有一些代码,这是我的幻灯片,我想知道的是你是否可以随机化图像,所以当你刷新页面时,它不会在同一图像上开始。

请给我提供有用的信息,如果你想给我看,请随意。

THNAKS伙计们!:)

<html>
<head>
<title>JQuery Cycle Plugin Sample</title>
<link rel="stylesheet" type="text/css" media="screen" href="../screen.css" />
<script type="text/javascript" src="../js2/jquery-1.3.js"></script>
<script type="text/javascript" src="../js2/jquery.cycle.all.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#myslides').cycle({
            fx: 'fade',
            speed: 2000,
            timeout: 2000
        });
    }); 
</script>
</head>
<body>
<div id="myslides"> 
    <img src="../images/capitol.jpg" />
    <img src="../images/flowers.jpg" />
    <img src="../images/countryscene.jpg" />
    <img src="../images/heartkush.jpg"/>
</div>
</body>
</html>

您可能希望将图像url保存在变量中(或从div检索它们,然后清除div),例如

var images = ['x.jpg', 'y.jpg', 'z.jpg'];

(或者更好——做一些预加载)。然后对

进行随机排序
function randomOrd(a,b)
{
   return (Math.round(Math.random())-0.5);
}
images.sort(randomOrd);

然后动态添加图片

for (var i in images)
{
   $('#myslides').append('<img src="'+images[i]+'" />');
}

,然后做幻灯片。最后的脚本可能如下所示:

<script>
    function randOrd(a,b)
    {
        return (Math.round(Math.random())-0.5);
    }
    $(document).ready(function(){
        var images = [];
        /* retrieve images */
        $('div#myslides img').each(function(){
            images.push($(this));
        });
        /* clear the div */
        $('div#myslides').empty();
        /* do the random sort of images */
        images.sort(randOrd);
        /* append to the div sorted images */
        for (var i in images)
        {
            $('div#myslides').append(images[i]);
        }
        /* do the slideshow */
        $('#myslides').cycle({
            fx: 'fade',
            speed: 2000,
            timeout: 2000
        });
    });
</script>
$("#myslides img").each(function() { 
      if (Math.random() >= 0.5) { $("#myslides").append($(this)); } 
});

这只是jQuery循环的众多选项之一。

random: true添加到选项中,如下:

$(document).ready(function(){
    $('#myslides').cycle({
        fx: 'fade',
        speed: 2000,
        timeout: 2000,
        random: true
    });
});