如何使用img元素的onerror属性

问题描述 投票:0回答:6

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
6个回答
205
投票

这有效:

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


3
投票

这实际上很棘手,特别是如果您计划返回图像 url 用于需要将字符串与

onerror
条件图像 URL 连接的用例,例如您可能想以编程方式在 CSS 中设置
url
参数。

诀窍在于图像加载本质上是异步的,因此

onerror
不会同步发生,即,如果您调用
returnPhotoURL
它会立即返回
undefined
,因为加载/处理图像加载的异步方法刚刚开始。

因此,您确实需要将脚本包装在 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;
        }
    });
}

2
投票

非常简单

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

1
投票

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

1
投票

在 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属性的实现,可以看这个视频:

如何制作完美的头像组件


0
投票

简单高效:

<img src="invalid_link" onerror="this.src='https://www.cvent-assets.com/brand-page-guestside-site/assets/images/venue-card-placeholder.png';" width="100%">

© www.soinside.com 2019 - 2024. All rights reserved.