【问题标题】:How does one use the onerror attribute of an img element如何使用 img 元素的 onerror 属性
【发布时间】:2011-12-28 19:40:24
【问题描述】:

CSS:

.posting-logo-div {
}
.posting-logo-img {
  height: 120px;
  width: 120px;
}
.posting-photo-div {
  height: 5px;
  width: 5px;
  position: relative;
  top: -140px;
  left: 648px;
}
.posting-photo-img {
  height: 240px;
  width: 240px;
}

HTML:

<div id="image" class="posting-logo-div">
  <img
    src="../images/some-logo1.jpg"
    onerror="this.src='../images/no-logo-120.jpg';"
    class="posting-logo-img"
  />
</div>
<div id="photo" class="posting-photo-div">
  <img
    src="../images/some-logo2.jpg"
    onerror="this.src='../images/no-logo-240.jpg';"
    class="posting-photo-img"
  />
</div>

这似乎在 Chrome 或 Mozilla 中不起作用,但在 IE 中起作用。

【问题讨论】:

    标签: html css image onerror


    【解决方案1】:

    这行得通:

    <img src="invalid_link"
         onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
    >
    

    现场演示: http://jsfiddle.net/oLqfxjoz/

    正如 Nikola 在下方评论中指出的那样,如果备份 URL 也无效,某些浏览器会再次触发“错误”事件,从而导致无限循环。我们可以通过简单地通过this.onerror=null; 取消“错误”处理程序来防止这种情况。

    【讨论】:

    • 如果 'placekitten.com/100/100' 不存在,这可能非常危险,因为浏览器会不断地敲击 'placekitten.com/100/100' url。请参阅stackoverflow.com/questions/92720/… 获取解决方案
    • @Neromancer 我在 Chrome 中测试过:jsfiddle.net/GvJh3/1。不会发生无限循环。
    • @ŠimeVidas:那是因为 Chrome 只计算一次 onerror,而所有其他浏览器都在不断地这样做——为了避免循环,它应该看起来像这样:onerror="this.onerror=null; this.src='http://placekitten.com/100/100';"
    • @NikolaBogdanović 很高兴知道。我已经更新了我的答案。
    • @harishannam 数据原始属性不会触发这些 URL 加载。你为此使用图书馆吗?如果是,该库应提供错误处理程序。
    【解决方案2】:

    这实际上很棘手,特别是如果您计划为需要将字符串与 onerror 条件图像 URL 连接的用例返回图像 url,例如您可能希望在 CSS 中以编程方式设置 url 参数。

    诀窍在于图像加载本质上是异步的,因此onerror 不会同步发生,即如果您调用returnPhotoURL,它会立即返回undefined bcs 加载/处理图像加载的异步方法刚刚开始.

    所以,你真的需要将你的脚本包装在一个 Promise 中,然后像下面这样调用它。注意:我的示例脚本做了一些其他的事情,但显示了一般概念:

    returnPhotoURL().then(function(value){
        doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
    }); 
    
    
    function returnPhotoURL(){
        return new Promise(function(resolve, reject){
            var img = new Image();
            //if the user does not have a photoURL let's try and get one from gravatar
            if (!firebase.auth().currentUser.photoURL) {
                //first we have to see if user han an email
                if(firebase.auth().currentUser.email){
                    //set sign-in-button background image to gravatar url
                    img.addEventListener('load', function() {
                        resolve (getGravatar(firebase.auth().currentUser.email, 48));
                    }, false);
                    img.addEventListener('error', function() {
                        resolve ('//rack.pub/media/fallbackImage.png');
                    }, false);            
                    img.src = getGravatar(firebase.auth().currentUser.email, 48);
                } else {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }
            } else {
                img.addEventListener('load', function() {
                    resolve (firebase.auth().currentUser.photoURL);
                }, false);
                img.addEventListener('error', function() {
                    resolve ('https://rack.pub/media/fallbackImage.png');
                }, false);      
                img.src = firebase.auth().currentUser.photoURL;
            }
        });
    }
    

    【讨论】:

      【解决方案3】:

      很简单

        <img onload="loaded(this, 'success')" onerror="error(this, 
       'error')"  src="someurl"  alt="" />
      
       function loaded(_this, status){
         console.log(_this, status)
        // do your work in load
       }
       function error(_this, status){
        console.log(_this, status)
        // do your work in error
        }
      

      【讨论】:

        【解决方案4】:

        将 product.invoice_url 替换为您的动态网址

        <img onerror="this.onerror=null;this.src='https://upload.wikimedia.org/wikipedia/commons/1/14/No_Image_Available.jpg';" [src]="product.invoice_url" class="img-thump" >
        
        css
        
          .img-thump{
            height: 120px;
            width: 170px;
          }
        

        【讨论】:

          【解决方案5】:

          在 ReactJS 中:

          const Avatar = ({className, src, alt, ...props}) => {
          const handleOnError = (e) => {
              e.target.src =
                "https://www.kindpng.com/picc/m/22-223863_no-avatar-png-circle-transparent-png.png";
          }
          return (
            <div>
              {src ? (
                <img
                  {...props}
                  className={`defaultClass ${className}`}
                  src={src}
                  alt={alt}
                  onError={handleOnError}
                />
              ) : (
                <img
                  {...props}
                  className={`defaultClass ${className}`}
                  src={
                    "https://www.kindpng.com/picc/m/22-223863_no-avatar-png-circle-transparent-png.png"
                  }
                  alt={alt}
                />
              )}
            </div>
          );}
          

          在上面的代码中,handleOnError 函数在检测到无效的src 链接时会被触发,因此我们可以在此函数中分配默认链接。

          如果你想在 react 中查看 onError 属性的实现,你可以查看这个视频:

          How to make a perfect Avatar Component

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-01-01
            • 2012-06-25
            • 1970-01-01
            • 1970-01-01
            • 2022-07-15
            • 1970-01-01
            • 2012-01-12
            相关资源
            最近更新 更多