我有两张备用图片和一张默认图片,以防找不到前两张图片。
<img
src='image1.png'
onError="this.onerror=null;this.src='image2.png';"
onError="this.onerror=null;this.src='default.png';" />
然后我测试了三个 <img />
我找到了 image1.png
和 image2.png
工作正常,但如果没有 image1.png
和 image2.png
, 默认图像 default.png
不显示。
关于如何使用多个替代图像(如我的上述案例)的任何提示?
最佳答案
您可能想改用 addEventListener
,跟踪您在可能图像数组中的位置。
<img src='image1.png'/>
<script>
function addFallbackSources(img, sources){
let idx = 0;
img.addEventListener("error", e=>{
if(idx >= sources.length) throw new Error("No images left to try");
img.src = sources[idx++];
});
}
addFallbackSources(document.querySelector('img'), ["image2.png", "default.png"]);
</script>
关于javascript - 为 img html 标签提供不止一种替代图像源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62786767/