简体   繁体   中英

Random slideshow using javascript

*Using JavaScript, implement an image slideshow viewer with the following requirements:

  • Name the HTML page as imageSlideShow.html and the corresponding JavaScript as imageSlideShow.js

  • The slideshow should consist of 5 different images.

  • Upon a click of a button, a different photo selected at random must be displayed on the webpage.

I have part of the script, but i cant figure out how to actually create a slideshow with a random button.

This is what I have for javascript:

var image1=New Image()
image1.src="image1.jpg"

var image2=New Image()
image1.src="image2.jpg"

var image3=New Image()
image1.src="image3.jpg"

var image4=New Image()
image1.src="image4.jpg"

var image5=New Image()
image1.src="image5.jpg"

and this is what the html part looks like:

<html>
    <head>
    </head>
    <body>
        <script type="text/Javascript" src="imageSlideShow.js"></script>
        <img src="image1.jpg" name="slide1">
        <br>
        <br>
        <button type="button" value="random" onclick="slideshow()" >Random Image</button>
    </body>
</html>

This isn't really a slideshow, it's just an image and you're changing the source randomly every time a button is clicked (calling a JavaScript function).

My suggestion is to use JavaScript to generate a random number between 1 and 5. Something like this:

HTML:

<img src="" id="image">

JavaScript:

function buttonClicked() {
    var randomNumber = Math.floor((Math.random()*5)+1);
    document.getElementById("image").src="image"+randomNumber+".jpg";
}

Math.floor((Math.random()*5)+1) generates a random number from 1 to 5. From here, document.getElementById uses randomNumber to randomly generate part of the source URL of the element. What you end up getting is an image source which is dependent on the number between 1 and 5 that you randomly generated.

you can randomize your images using this:

   function shuffle(o){ //v1.0
        for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o;
    };

var imgs ["image1.jpg","image2.jpg","image3.jpg","image4.jpg","image5.jpg"];

imgs = shuffle(imgs);

var pos = 0;

slideshow(){
   image1.src=imgs[pos];
   pos = (pos+1)%imgs.length;
}

this is the basic idea, you can customize this script to your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM