[英]Handling multiple image fallbacks in Javascript
有沒有辦法在純 Javascript 或 React 中處理多個圖像回退?
我知道我們可以使用onError().
處理一張后備圖像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 中保留回退。 您可以將回退放入元素本身的數據屬性中,並通過 dataset 屬性檢索它
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" />
對於反應,你基本上會做同樣的事情,但通過他們的語法,完整的演示
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" />
還有很多其他很好的答案。 任何需要分享我如何解決它的人,試試這個。
<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 作為變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.