gpt4 book ai didi

javascript - 在 Javascript 中处理多个图像后备

转载 作者:行者123 更新时间:2023-12-01 01:43:03 26 4
gpt4 key购买 nike

有没有办法在纯 Javascript 或 React 中处理多个图像回退?

我知道我们可以使用 onError() 处理一个后备图像。如果我们想要处理另一张后备图像怎么办?

提前致谢!

最佳答案

每次设置导致错误的 src 时,都会调用图像的 onerror 回调。

因此,对于原生 js 解决方案,您可以保留一个后备图像列表,并在每次调用回调时增量地遍历该列表,直到耗尽为止。

var fallbacks = ["1.jpg","2.jpg","https://placebear.com/g/100/100","4.jpg"];
var image = new Image;
image.dataset["fallback"] = 0;
image.onerror = function(){
console.log("onerror triggered");
var fallbackIndex = this.dataset["fallback"];

//check to see if we exhausted the fallbacks
if(fallbackIndex > fallbacks.length-1) return;

//set the fallback image
this.src = fallbacks[fallbackIndex];

//increment the index incase onerror is called again
image.dataset["fallback"]++;
}

document.body.appendChild(image);
image.src = "doesntexist.jpg";

请注意,您不必在 JavaScript 中保留后备。您可以将后备放入元素本身的数据属性中,并通过数据集属性检索它

document.querySelector("img").addEventListener("error",function(){
var fallbackIndex = this.dataset["fallback"];
var fallbacks = this.dataset["fallbacks"].split(",");

if(fallbackIndex > fallbacks.length-1) return;
this.src = fallbacks[fallbackIndex];
this.dataset["fallback"]++;
});
<img src="" data-fallback="0" data-fallbacks="1.jpg,2.jpg,https://placebear.com/g/100/100,4.jpg" />

对于 React,你基本上会做同样的事情,但是通过它们的语法,full demo

class ImageWithFallbacks extends React.Component {
constructor(props) {
super(props);
this.state = {
src: props.src,
fallbackIndex: 0
}
this.props.fallbacks = this.props.fallbacks.split(",");
}
onError() {
console.log("errored",this.state.fallbackIndex);
if(this.state.fallbackIndex > this.props.fallbacks.length){
return;
}
this.setState({
src: this.props.fallbacks[this.state.fallbackIndex],
fallbackIndex: this.state.fallbackIndex+1
});
}
render() {
return <img src={this.state.src} onError={()=>this.onError()} />;
}
}
<小时/>
<ImageWithFallbacks src="nonexistent.jpg" fallbacks="1.jpg,2.jpg,https://placebear.com/g/100/100,4.jpg" />

关于javascript - 在 Javascript 中处理多个图像后备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52231187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com