开发者

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

开发者 https://www.devze.com 2023-04-12 08:23 出处:网络
Here i have some code which is my slideshow and what i am wondering is whether you can randomize the images so it doesn\'t start on the same image when you refresh the page.

Here i have some code which is my slideshow and what i am wondering is whether you can randomize the images so it doesn't start on the same image when you refresh the page.

Please provide me with useful info and if you wish to show me feel free.

THNAKS GUYS! :)

<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
        });
  开发者_Go百科  }); 
</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>


You may want to hold image urls in a variable (or retrieve them from your div and clear the div afterwards), say

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

(or even better - do some preloading). Then do a random sort

function randomOrd(a,b)
{
   return (Math.round(Math.random())-0.5);
}
images.sort(randomOrd);

then dynamically add images

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

and then do the slideshow. The final script may look like this:

<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)); } 
});


This is just one of the many options that jQuery cycle has.

Add random: true to the options like so:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号