简体   繁体   中英

How to make a button display random images on the slideshow

I have here a simple program that displays random images that are in order, with two buttons that enable you to switch from an ascending order and then descending order. Now, I want to implement a random button that will display a random image of the selection but, I can't seem to figure out how. Below is my code:

 var images = [ "1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg" ]; var num = 0; function next() { var slider = document.getElementById("slider"); num++; if (num >= 8) { num = 0; } slider.src = images[num]; } function prev() { var slider = document.getElementById("slider"); num--; if (num < 0) { num = 7; } slider.src = images[num]; } function random() { //where the code is supposed to be }
 <head> <title>Laboratory Exercise 7</title> </head> <body> <div> <button onClick="prev()"> &lt;--- </button> <img id="slider" SRC="1.jpg" width="200px" height="100px" /> <button onClick="next()"> ---&gt; </button> <button onClick="random()"> Random </button> </div> </body>

There are your problem decission:

function random(min, max) {
  return Math.round(Number(min + Math.random() * (max - min)));
}

function random() {
  var slider = document.getElementById("slider");  
  slider.src = images[random(0, 7)];
}

The first function is returning random number from 0 to 7 (all your images in arrays) and after that the second function set random number like index and take a image from the array with that index.

But you also can minimaze your code like that, just take out slider variable outside every function.

var slider = document.getElementById("slider") ;

I hope that it will help to you!

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