简体   繁体   English

在 Javascript 中处理多个图像回退

[英]Handling multiple image fallbacks in Javascript

Is there a way to handle multiple image fallbacks in plain Javascript or in React?有没有办法在纯 Javascript 或 React 中处理多个图像回退?

I know we can handle one fallback image with onError().我知道我们可以使用onError().处理一张后备图像onError(). What if we want to do another fallback image?如果我们想做另一个后备图像怎么办?

Thanks in advance!提前致谢!

The image's onerror callback will be called each time you set a src that causes an error.每次设置导致错误的 src 时,都会调用图像的 onerror 回调。

So for a native js solution you can keep a list of fallback images, and incrementally go through that list each time the callback is called until it is exhausted.因此,对于原生 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";

Note you don't have to keep the fallbacks in javascript.请注意,您不必在 javascript 中保留回退。 You could place the fallbacks into a data attribute on the element itself and retrieve it through the dataset property您可以将回退放入元素本身的数据属性中,并通过 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" />

For react you would basically do the same thing but through their syntax, 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" />

There are many other good answers.还有很多其他很好的答案。 Anyone who needs to share how I solved it, try this.任何需要分享我如何解决它的人,试试这个。

<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';
       }
    }}
/>

I use data-src as a variable.我使用 data-src 作为变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM