简体   繁体   English

使用 JavaScript 动态加载文件夹/子文件夹中的所有图像

[英]Dynamically load all images from folder/subfolders with JavaScript

I have an /img directory on my Github Pages website.我的 Github Pages 网站上有一个/img目录。 There are about 50 images in /img and sub folders that I want to display in a grid on a page.我想在页面上的网格中显示/img和子文件夹中大约有 50 张图像。 I have no interest in typing out the following 50 times for each image...我没有兴趣为每个图像输入以下 50 次......

  <a href="...">
     <img alt=".." src="img/...">
  </a>

... especially since I will be adding and removing images over time. ...特别是因为我将随着时间的推移添加和删除图像。

How do dynamically create the HTML code with JavaScript?如何使用 JavaScript 动态创建 HTML 代码? I obviously can't use PHP since this is Github Pages.我显然不能使用 PHP,因为这是 Github Pages。

I have already tried AJAX and requirejs but couldn't get anything to work.我已经尝试过 AJAX 和 requirejs,但没有任何效果。

You can do this by using Github Actions你可以通过使用Github Actions来做到这一点

In your repository add a new file update-image-list.yml under path .github/workflows/ (you may need to create the folders)在您的存储库中,在路径.github/workflows/下添加一个新文件update-image-list.yml (您可能需要创建文件夹)

Put this code into the file:将此代码放入文件中:

name: Update Image List
on:
  push
jobs:
  updateImageList: # you can put any name here
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2 # Checkout repo
      - shell: bash
        run: ls -Rpm1 ./img/ > images.txt # Saving file list into a file
      - name: Save changes
        uses: actions-go/push@v1 # pushing the changes to the repo
        with:
          force: true
          commit-files: images.txt
          commit-message: Updating image list

Now, every time you push something to your repo this script will be executed saving an up-to-date list of the image files into images.txt file using ls command line and then pushing the file to the repo.现在,每次你向你的 repo 推送一些东西时,都会执行这个脚本,使用ls命令行将最新的图像文件列表保存到images.txt文件中,然后将文件推送到 repo。 The content will be something like:内容将类似于:

images.txt图像.txt

./img/:
image1.jpg
child-folder/
image2.png
image3.jpg

./img/child-folder:
image4.jpg

Now that you have the list of image files into images.txt , you just have to get the file to the frontend side and process its content现在您已将图像文件列表放入images.txt ,您只需要将文件传送到前端并处理其内容

Something like this works:像这样的工作:

In your HTML:在您的 HTML 中:

<div class="images" id="images"></div>

<script>
function loadImages() {
    const xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            const fileList = this.responseText.split('\n'); // Split by lines
            let currentFolder = '';

            const filePaths = fileList
                .map(f => { // Build correct path for each file
                    let filePath = '';

                    if (f) {
                        if (f[0] === '.') {
                            currentFolder = f.replace('.', '').replace(':', '/');
                        }
                        else if (f[f.length - 1] !== '/') {
                            filePath = `${location.href}${currentFolder}${f}`;
                        }
                    }
          
                    return filePath;
                })
                .filter(f => f); // Remove empty lines
      
            const imagesContainer = document.getElementById('images');
      
            filePaths.map(f => { // Create and put images to the DOM
                const img = document.createElement('IMG');
                img.src = f;
                imagesContainer.appendChild(img);
            });
        }
    };

    xhttp.open("GET", "images.txt", true);
    xhttp.send();
}

loadImages();
</script>

But of course you can use any library/framework to do the same但是当然你可以使用任何库/框架来做同样的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM