是否有任何方法在HTML <img>标记中呈现默认图像,以防src属性无效(仅使用HTML)?如果不是,你会用什么轻量级的方式来解决这个问题?


当前回答

好了! ! 我发现这种方法很方便,检查图像的高度属性为0,然后你可以用默认的图像覆盖src属性: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

 image.setAttribute('src','../icons/<some_image>.png');
  //check the height attribute.. if image is available then by default it will 
  //be 100 else 0
  if(image.height == 0){                                       
       image.setAttribute('src','../icons/default.png');
  }

其他回答

你要求只有HTML的解决方案…

<!DOCTYPE html PUBLIC "-//W3C//DTD html 4.01//EN" " http://www.w3.org/TR/html4/strict.dtd " > < html lang =“en”> <头> <标题>对象测试< /名称> <meta http-equiv=" content - type " content="text/html;charset = utf - 8”> > < /头 <身体> < p > <object data="https://stackoverflow.com/does-not-exist.png" type="image/png"> <img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45" alt="Stack Overflow徽标和图标等"> < /对象> < / p > < /身体> < / html >

由于第一个图像不存在,将显示回退(在这个网站上使用的精灵*)。如果你用的是不支持object的旧浏览器,它会忽略那个标签,使用img标签。查看caniuse网站了解兼容性。从IE6+开始的所有浏览器都广泛支持该元素。

*除非图片的URL改变了(再次),在这种情况下,你可能会看到alt文本。

<img style=“background-image: url(image1), url(image2);”></img>

使用背景图像,让您可以添加多个图像。 我的情况: Image1是主图像,这将从某个地方获取(浏览器执行请求) Image2是加载image1时显示的默认本地图像。 如果image1返回任何类型的错误,用户将看不到任何更改,这对于用户体验来说是干净的

没有办法确定无数的客户端(浏览器)将试图查看您的页面。需要考虑的一个方面是,电子邮件客户端实际上是web浏览器,可能无法处理这种诡计……

因此,你也应该包括一个alt/文本的默认宽度和高度,就像这样。这是一个纯HTML解决方案。

alt="NO IMAGE" width="800" height="350"

所以另一个好的答案可以修改如下:

<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';" alt="NO IMAGE" width="800" height="350">

我在Chrome中有对象标签的问题,但我想这也适用于此。

你可以进一步样式的alt/文本非常大…

所以我的答案是使用Javascript和一个不错的alt/text回退。

我还发现这个很有趣:如何设置图像的alt属性

好了! ! 我发现这种方法很方便,检查图像的高度属性为0,然后你可以用默认的图像覆盖src属性: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image

 image.setAttribute('src','../icons/<some_image>.png');
  //check the height attribute.. if image is available then by default it will 
  //be 100 else 0
  if(image.height == 0){                                       
       image.setAttribute('src','../icons/default.png');
  }

使用Jquery,你可以这样做:

$(document).ready(function() {
    if ($("img").attr("src") != null)
    {
       if ($("img").attr("src").toString() == "")
       {
            $("img").attr("src", "images/default.jpg");
       }
    }
    else
    {
        $("img").attr("src", "images/default.jpg");
    }
});