Currently the image slideshow gallery allows for the browsing of the image by clicking arrow buttons to view previous or the next picture.
Is there a way to make it so that a random image loads everytime the website is visit? Instead of always starting from page 1, the website will start from page 2 or 3 for example.
Here is the HTML, CSS, and javascript.
HTML
<div class="slideshow-container">
<!-- Full-width images with number and caption text -->
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="images/art/38.jpg" style="width: 75%" />
<div class="text">1</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="images/art/43.jpg" style="width: 75%" />
<div class="text">2</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="images/art/39.jpg" style="width: 75%" />
<div class="text">3</div>
</div>
<!-- Next and previous buttons -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
Javascript
var slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides((slideIndex += n));
}
// Thumbnail image controls
function currentSlide(n) {
showSlides((slideIndex = n));
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = slides.length;
}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
CSS
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
.prev {
left: 0;
border-radius: 3px 0 0 3px;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
You can use
var slideIndex = Math.floor(Math.random() * slides.length) + 1;
This assigns the variable slideIndex
to a random integer between 1 and the number of slides. Note that you will have to put
var slides = document.getElementsByClassName("mySlides");
before this in order for it to work.
Or you could just replace slides.length
with the number of elements you have, but you will have to update this every time you add or remove an element.
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.