【问题标题】:onerror event using background: url()使用背景的 onerror 事件:url()
【发布时间】:2014-04-12 19:22:05
【问题描述】:

如果找不到源图像,有没有办法显示替代图像?我知道要做到这一点是通过执行以下操作:

<img src="imagenotfound.gif" alt="Image not found" onError="this.src='imagefound.gif';" />

但是如果你在做这样的事情,如果有错误或者没有找到图像,你怎么能捕捉到呢?

<div style="background:url('myimage.gif')"></div>

【问题讨论】:

    标签: html css image background onerror


    【解决方案1】:

    如果myimage.gif 不透明,您可以使用多个背景:

    background: url('myimage.gif'), url('fallback.gif');
    

    这样fallback.gif 只有在myimage.gif 不可用时才可见。

    请注意,即使myimage.gif 可用,也可以下载fallback.gif


    另外,尽管没有得到广泛支持,但 CSS Images 3 引入了the image() notation

    background: image('myimage.gif', 'fallback.gif');
    

    多个&lt;image-decl&gt;s可以用逗号分隔,在 在这种情况下,函数代表第一个不是 invalid image.

    【讨论】:

    • 这很挑剔,但第二张图片的更好名称是imagenotfound.gif,因为它会在第一张图片不可用时显示
    • @oriol 无论如何都会在找不到第一个图像时防止控制台中的 404 消息
    • @jpussacq 根据caniuse,94.58% 的浏览器支持多种背景。
    • CSS3 还没有真正实现 image()。仅参考建议的候选规范。
    • image() 实际上已被推迟到 CSS 4 图片:w3.org/TR/css-images-4/#image-notation,目前完全不受支持:caniuse.com/#feat=mdn-css_types_image_image
    【解决方案2】:

    有背景图片,没有事件;你自己检查一下。

    Make an (XML)HTTP request,如果您收到an error status code 的响应或根本没有响应(超时后),请使用其他图像资源。这种方法受到Same-Origin Policy 的限制。

    【讨论】:

      【解决方案3】:

      您还可以使用虚拟图像并从那里使用 onerror 事件...

              $imageFoo = '
              <div id="' . $uniqueId . '"
                   style="
                      background-image: url(//foo.lall/image.png);
                      -webkit-background-size: contain;
                      -moz-background-size: contain;
                      -o-background-size: contain;
                      background-size: contain;
                      background-position: center;
                      background-repeat: no-repeat;
                   "
              ></div>
              <!-- this is a helper, only needed because "background-image" did not fire a "onerror" event -->
              <img style="display: none;" 
                   src="//foo.lall/image.png" 
                   onerror="var fallbackImages = $(this).data(\'404-fallback\'); $(\'#' . $uniqueId . '\').css(\'background-image\', \'url(\' + fallbackImages + \')\');"
                   data-404-fallback="//foo.lall/image_fallback.png"
              >
              ';
      

      【讨论】:

        猜你喜欢
        • 2021-04-11
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-14
        • 1970-01-01
        • 1970-01-01
        • 2018-06-04
        相关资源
        最近更新 更多