You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在通过Unsplash API加载图片前后显示/隐藏加载动画?

问题分析

你的代码存在几个关键问题导致加载动画无法正常工作:

  • 拼接完图片HTML后立刻调用隐藏加载动画的方法,此时浏览器仅开始发起图片请求,并未完成加载,加载动画直接被隐藏,用户看不到加载状态。
  • HTML中#num是<div>元素,无法让用户输入数字,需要改为输入框。
  • 隐藏加载动画的方法中错误使用display: "hidden",正确值应为display: "none";同时混用visibility和display控制元素显示,逻辑混乱。
解决方案

核心思路是监听所有图片的加载完成事件,等全部图片加载完毕后再隐藏加载动画,同时修正HTML和JS中的细节错误:

修正后的HTML

<!-- 输入框改为number类型,限制最小数量 -->
<input type="number" id="num" min="1" value="1">
<button id="btn">加载图片</button>
<div id="output">
  <img src="https://media.tenor.com/lwoULCdn-y4AAAAC/placeholder-text.gif" id="load">
</div>

修正后的JS

const imgNumInput = document.querySelector('#num')
const btn = document.querySelector("#btn")
const output = document.querySelector("#output")
const loader = document.querySelector("#load")
const baseUrl = "https://source.unsplash.com/random"

// 初始化隐藏加载动画
loader.style.display = 'none';

function showLoader() {
  loader.style.display = 'block';
}

function hideLoader() {
  loader.style.display = 'none';
}

function loadImages() {
  // 清空之前的图片
  output.innerHTML = '';
  // 显示加载动画
  showLoader();
  
  const imgCount = Number(imgNumInput.value);
  let loadedCount = 0;

  for (let i = 0; i < imgCount; i++) {
    // 添加随机参数避免Unsplash返回重复图片
    const imgUrl = `${baseUrl}?${Math.random()}`;
    const img = document.createElement('img');
    img.src = imgUrl;
    
    // 监听单个图片加载完成事件
    img.addEventListener('load', () => {
      loadedCount++;
      // 所有图片加载完成后隐藏动画
      if (loadedCount === imgCount) {
        hideLoader();
      }
    });
    
    // 处理图片加载失败的情况(可选)
    img.addEventListener('error', () => {
      loadedCount++;
      if (loadedCount === imgCount) {
        hideLoader();
      }
    });
    
    output.appendChild(img);
  }
}

btn.addEventListener("click", loadImages)

关键说明

  • 改用document.createElement创建图片元素,方便绑定load/error事件,统计加载完成的数量。
  • 给Unsplash的URL添加随机参数?${Math.random()},避免同时请求多张图片时返回重复内容。
  • 每次点击加载按钮时先清空输出容器,避免图片叠加。
  • 同时处理图片加载失败的情况,防止因单张图片加载失败导致加载动画一直显示。

内容的提问来源于stack exchange,提问作者Apoorv Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:40:28