【问题标题】:How to handle image not found error in html5 picture tag如何处理 html5 图片标签中的图片未找到错误
【发布时间】:2019-03-09 00:43:43
【问题描述】:

我正在尝试使用以下代码:

<picture>
    <source media="(min-width: 1200px)" srcset="https://example.com/images/abc.jpg?resize=169,169">
    <source media="(min-width: 992px)" srcset="https://example.com/images/cde.jpg?resize=132,132">
    <img src="index_files/red_1.jpg" alt="Red 1">
</picture>

我面临的问题是当 abc.jpg 或 cde.jpg 不可用时,它应该显示默认图像,例如 default.jpg 而不是 red_1.jpg 我在网站上提到了其他类似的主题,但我不知道如何在 html 的帮助下处理问题。

在那种情况下是否可以使用onerror,如果可以,在哪里以及如何使用?

【问题讨论】:

  • 这个SO Question 可能会有所帮助。但是你需要使用JavaScript

标签: html image


【解决方案1】:
<picture>
  <source srcSet="image.webp" type="image/webp" />
  <source srcSet="image.jpeg" type="image/jpeg" />
  <source srcSet="image.png" type="image/png" />
  <img srcSet="image.jpg" onError={(e) => {
    e.target.onerror = null;
    e.currentTarget.parentNode.children[0].srcset = e.target.src;
    e.currentTarget.parentNode.children[1].srcset = e.target.src;
    e.currentTarget.parentNode.children[2].srcset = e.target.src;
    e.currentTarget.parentNode.children[3].srcset = e.target.src;
  }} />
</picture>

【讨论】:

    【解决方案2】:

    是的,use the onerror event。然后,您可以简单地更改src 属性:

    let image = document.querySelector('img');
    image.onerror = function() {
      if (this.src === 'default1.png') this.src = 'default2.png';
      else if (this.src !== 'default2.png') this.src = 'default1.png';
    }
    

    这会将图像的src 从原来的任何内容更改为'default1.png',然后,如果再次触发,则更改为'default2.png'

    【讨论】:

    • 有两个 标签,要求是 - 如果第一个 标签有错误,则显示 default1.jpg,如果第二个 标签错误,则显示 default2.jpg。
    • 我无法使用您的解决方案。
    • @team 我确实通过简单地添加一个 if 语句来编辑我的答案。在这一点上只是逻辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多