简体   繁体   中英

Skip Image if doesn't exist (carousel)

I'm trying to display images from a folder, But when the image does not exist. I want it to skip to the next one. I'm using 'display none' here. Below is the code. Thanks in Advance. Sorry if there's any mistake.

<div class="w3-content w3-section" style="position:fixed; height: 100%; width:100%;">
<img class="mySlides" src="uploads/1.JPG" align="middle" >
<img class="mySlides" src="uploads/2.JPG" align="middle">
<img class="mySlides" src="uploads/3.JPG" align="middle">
<img class="mySlides" src="uploads/4.JPG" align="middle">
</div>

<script>

var myIndex = 0;
carousel();

function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
   x[i].style.display = "none";  

}
myIndex++;
if (myIndex > x.length) {myIndex = 1}    
x[myIndex-1].style.display = "block";  //For Eg if 1.JPG is not found it displays black screen for 5secs.
  setTimeout(carousel, 5000); // Change image every 5 seconds

 }
</script>

Add attribute onerror in every img tag

<div class="w3-content w3-section" style="position:fixed; height: 100%; width:100%;">
<img class="mySlides" src="uploads/1.JPG" onerror="this.remove()" align="middle" >
<img class="mySlides" src="uploads/2.JPG" onerror="this.remove()" align="middle">
<img class="mySlides" src="uploads/3.JPG" onerror="this.remove()" align="middle">
<img class="mySlides" src="uploads/4.JPG" onerror="this.remove()" align="middle">
</div>

Hope it'll help you out.

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