有没有办法在普通Javascript或React中处理多个图像后备?
我知道我们可以使用onError().
处理一个后备图像,如果我们想做另一个后备图像怎么办?
提前谢谢!
答案 0 :(得分:2)
每次设置导致错误的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中。您可以将备用广告放到元素本身的data属性中,然后通过数据集属性进行检索
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" />
为了做出反应,您基本上会做同样的事情,但是通过它们的语法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" />
答案 1 :(得分:0)
还有很多其他好的答案。任何需要分享我如何解决它的人,试试这个。
<img
src={1st Image url}
data-src={2nd Image url}
alt=""
className=""
onError={e => {
if(e.target.dataset.src === 'resize') {
e.target.src = 'this is your final image. if 1st 2nd all 404, then this image will be shown'
e.target.dataset.src = 'null'
}
if(e.target.dataset.src !== 'null') {
e.target.src = e.target.dataset.src;
e.target.dataset.src = 'resize';
}
}}
/>
我使用 data-src 作为变量。