如何在modal中显示spinner直到响应返回、图片加载完成
实现思路
- 模态框内部同时预设spinner加载动画和图片元素两个节点
- 默认状态下隐藏图片,显示spinner
- 监听图片的
load事件,触发后切换两个元素的显示状态:隐藏spinner,显示图片 - 若需要兼容加载失败场景,可额外监听
error事件做降级提示处理
原生JS实现示例
<!-- 模态框结构 --> <div class="modal"> <!-- 加载动画 默认显示 --> <div class="spinner" id="loadingSpinner"></div> <!-- 图片 默认隐藏 --> <img src="" alt="目标图片" id="modalImg" style="display: none;"> </div>
// 传入图片资源地址即可触发加载逻辑 function loadModalImg(imgUrl) { const spinner = document.getElementById('loadingSpinner') const modalImg = document.getElementById('modalImg') // 加载前重置状态 spinner.style.display = 'block' modalImg.style.display = 'none' // 赋值图片地址触发资源请求 modalImg.src = imgUrl // 图片加载完成后切换显示 modalImg.onload = function() { spinner.style.display = 'none' modalImg.style.display = 'block' } // 可选:加载失败处理逻辑 modalImg.onerror = function() { spinner.style.display = 'none' // 可在此处插入加载失败提示 } }
Vue3 实现示例
<template> <div class="modal"> <div class="spinner" v-if="isLoading"></div> <img :src="imgUrl" alt="目标图片" v-show="!isLoading" @load="isLoading = false" @error="handleLoadError" > </div> </template> <script setup> import { ref } from 'vue' const isLoading = ref(true) const imgUrl = ref('') // 打开模态框时调用,传入图片地址 const openModal = (url) => { isLoading.value = true imgUrl.value = url } const handleLoadError = () => { isLoading.value = false // 加载失败处理逻辑 } </script>
React 实现示例
import { useState, useEffect } from 'react' function Modal({ imgUrl }) { const [isLoading, setIsLoading] = useState(true) // 图片地址变化时重置加载状态 useEffect(() => { setIsLoading(true) }, [imgUrl]) return ( <div className="modal"> {isLoading && <div className="spinner"></div>} <img src={imgUrl} alt="目标图片" style={{ display: isLoading ? 'none' : 'block' }} onLoad={() => setIsLoading(false)} onError={() => setIsLoading(false)} /> </div> ) }
注意:浏览器缓存的图片也会正常触发
load事件,不需要额外适配缓存场景。
内容的提问来源于stack exchange,提问作者greenapple
相关产品推荐
相关产品推荐

