如何使用 img 元素的 onerror 属性

新手上路,请多包涵

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 中有效。

原文由 Shahrukh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 853
2 个回答

这有效:

 <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; 使“错误”处理程序无效来防止这种情况。

原文由 Šime Vidas 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

诀窍是图像加载本质上是异步的,所以 onerror 不会同步发生,即如果你调用 returnPhotoURL 它立即返回 undefined 异步方法 b加载/处理图像加载才刚刚开始。

所以,你真的需要将你的脚本包装在一个 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;
        }
    });
}

原文由 Ronnie Royston 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题