简体   繁体   中英

Displaying multiple images in html from folder

Hi I'm new to html and I was just making something for fun as a practice. I'm trying to display multiple images in html, and I wasn't sure how. For example,

  <img src="/images/1/1.jpg" class="center">
  <img src="/images/1/2.jpg" class="center">
  <img src="/images/1/3.jpg" class="center">
  <img src="/images/1/4.jpg" class="center">

I have this right now, but I don't want to write this every time. I was wondering how I would do it. Could I use JavaScript or php or anything to put all images in the folder at once?

simple code on PHP:

<?php
  $refFolder = "/images/1/";
  function folderList($Path) {
    return  array_slice(scandir($Path,SCANDIR_SORT_ASCENDING), 0); 
  }
  foreach(folderList($refFolder) as $file) { 
    $Z_info = pathinfo($file, PATHINFO_FILENAME);
    $Z_type = pathinfo($file, PATHINFO_EXTENSION);
    if ($Z_type == 'jpg') { 
?>
    <img class="center" 
      src="<? echo $refFolder.$file; ?>" 
      alt="<? echo $Z_info; ?>" 
    />
<?php } } ?>

You need to create a rest endpoint which returns you the list of all the images in your folder and then you could loop through the array and add your images to the DOM dynamically.

Ex:

const folder = '/folder';
const arr = ['img1.jpg', 'img2.jpg'];

arr.forEach(image => {
   const imgCntr = document.getElementById('imgCntr'); // Div which contains the iamges
   const img = document.createElement("IMG");
   img.src = `${folder}/${image}`;
   imgCntr.appendChild(img)
});

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