如何在javascript中根据其名称显示png图像?

问题描述

我有一个包含png图像和其他几种文件文件夹。我只想按其名称顺序显示png图像,该怎么办?所有图像均以数字结尾;例如,每个图像的标题为“ image_001”,“ image_002”,依此类推。现在,我将所有图像分组在一个类中,如下所示,但是如果不想包含任何其他文件类型,我不想不必添加每个图像。预先谢谢你。

 <section>
        <img class="pics" src="imgfolder/picture_001.png" style="width:80%">
        <img class="pics" src="imgfolder/picture_002.png" style="width:80%">
        <img class="pics" src="imgfolder/picture_003.png" style="width:80%">
 </section>

<script type="text/javascript">
        var index = 0;
        change();

        function change() {
             var images = document.getElementsByClassName('pics');

             for(var i = 0; i < images.length; i++) { 
                 images[i].style.display = "none"; 
             }       
             index++;

             if(index > images.length) { 
                 index = 1; 
             }

             images[index - 1].style.display = "block";

             setTimeout(change,3000);
         }
</script>

解决方法

注释JS代码及其功能。我已经使用您在问题中使用的相同文件结构对它进行了测试,但是您可以在JS第9行中对其进行更改。

<section id="img-container"></section>
const numOfPictures = 3; // The number of pictures in folder
const picturesNumberLength = 3; // "000"
let imageIndex = 1;
let imagesArray = [];
const imagesContainer = document.getElementById("img-container"); // Get the images container,has id "img-container"

for (let i = 1; i < numOfPictures + 1; i++) { // Starts at a 1 index "001"
  const img = document.createElement("img"); // Create an image element
  img.src = `imgfolder/picture_${(i+"").padStart(picturesNumberLength,"0")}.png`; // Set the source to "imgfolder/picture_001" or other number,works up to 999
  img.classList.add("pics"); // Add the pics class
  img.style.width = "80%"; // Sets width to 80%
  img.style.display = "none"; // Turns off displaying it
  imagesContainer.appendChild(img); // Puts the image in the image container
  imagesArray.push(img); // Push the reference to the array
}
imagesArray[0].style.display = "block"; // Display the first block
setInterval(() => { // Every 3000ms (3secs),do this
  imagesArray[imageIndex].style.display = "block"; // Turn displaying on
  if (imageIndex > 0) imagesArray[imageIndex-1].style.display = "none"; // Turn the previous one off
  else imagesArray[numOfPictures-1].style.display = "none";
  imageIndex++; // Change the index
  if (imageIndex >= numOfPictures) imageIndex = 0; // Go back to the beginning after going to the end
},3000);