Html 如何使用 img 元素的 onerror 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8124866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:30:47  来源:igfitidea点击:

How does one use the onerror attribute of an img element

htmlcssimageonerror

提问by Shahrukh

CSS:

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:

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>

This doesn't seem to work in Chrome or Mozilla but does work in IE.

这似乎不适用于 Chrome 或 Mozilla,但适用于 IE。

回答by ?ime Vidas

This works:

这有效:

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

Live demo:http://jsfiddle.net/oLqfxjoz/

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

As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;.

正如 Nikola 在下面的评论中指出的那样,如果备份 URL 也无效,某些浏览器将再次触发“错误”事件,这将导致无限循环。我们可以通过简单地通过this.onerror=null;.

回答by Ronnie Royston

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerrorcondition image URL, e.g. you might want to programatically set the urlparameter in CSS.

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

The trick is that image loading is asynchronous by nature so the onerrordoesn't happen sunchronously, i.e. if you call returnPhotoURLit immediately returns undefinedbcs the asynchronous method of loading/handling the image load just began.

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

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

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

回答by Mustkeem K

very simple

很简单

  <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
  }