首页 文章

如果html <img>的src属性无效,请输入默认图像?

提问于
浏览
204

有没有办法在HTML <img> 标记中呈现默认图像,以防 src 属性无效(仅使用HTML)?如果没有,那么你的轻量级解决方法是什么?

19 回答

  • 2

    你问过一个只有HTML的解决方案......

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    
    <html lang="en">
    
    <head>
      <title>Object Test</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    
    <body>
    
      <p>
        <object data="http://stackoverflow.com/does-not-exist.png" type="image/png">
          <img src="https://appharbor.com/assets/images/stackoverflow-logo.png" alt="example">
        </object>
      </p>
    
    </body>
    
    </html>
    

    由于第一个图像没有使用不支持object的旧浏览器,因此它将忽略该标记并使用 img 标记 . 有关兼容性,请参见caniuse网站 . 截至2018年,这个元素得到了ie6的所有浏览器的广泛支持 .

  • 0

    这对我很有用 . 也许你想用JQuery挂钩事件 .

    <img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">
    

    更新了jacquargs错误保护

    Updated: CSS only solution 我最近看到Vitaly Friedman演示了一个我不知道的优秀CSS解决方案 . 我们的想法是将 content 属性应用于损坏的图像 . 通常 :after:before 不适用于图像,但是当它们重新应用时're broken, they' .

    <img src="nothere.jpg">
    <style>
    img:before {
        content: ' ';
        display: block;
        position: absolute;
        height: 50px;
        width: 50px;
        background-image: url(ishere.jpg);
    </style>
    

    演示:https://jsfiddle.net/uz2gmh2k/2/

    正如小提琴所示,破坏的图像本身并没有被删除,但这可能解决了大多数情况下没有任何JS也没有CSS的问题 . 如果您需要在不同位置应用不同的图像,只需区分一个类: .my-special-case img:before { ...

  • 49

    在Spring in Action 3rd Ed中找到了这个解决方案 .

    <img src="../resources/images/Image1.jpg" onerror="this.src='../resources/images/none.jpg'" />

    Update: 这不是HTML唯一的解决方案... onerror 是javascript

  • -1
    <style type="text/css">
    img {
       background-image: url('/images/default.png')
    }
    </style>
    

    请务必输入图像尺寸以及是否要图像平铺 .

  • 9

    我认为只使用HTML是不可能的 . 但是使用javascript这应该是可行的 . Bassicly我们遍历每个图像,测试它是否完整,如果它的naturalWidth是零那么这意味着它没有找到 . 这是代码:

    fixBrokenImages = function( url ){
        var img = document.getElementsByTagName('img');
        var i=0, l=img.length;
        for(;i<l;i++){
            var t = img[i];
            if(t.naturalWidth === 0){
                //this image is broken
                t.src = url;
            }
        }
    }
    

    像这样使用它:

    window.onload = function() {
        fixBrokenImages('example.com/image.png');
     }
    

    在Chrome和Firefox中测试过

  • 1

    If you're using Angular/jQuery then this might help...

    <img ng-src="{{item.url}}" altSrc="{{item.alt_url}}" onerror="this.src = $(this).attr('altSrc')">
    

    Explanation

    假设 item 的属性 url 可能为null,那么当它出现时,图像将显示为已损坏 . 这会触发 onerror 属性表达式的执行,如上所述 . 您需要覆盖 src 属性,如上所述,但您需要jQuery来访问您的altSrc . 无法使用vanilla JavaScript .

    可能看起来有点hacky但是在我的项目上节省了一天 .

  • 254
    <img style="background-image: url(image1), url(image2);"></img>
    

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

  • 0

    angular2:

    <img src="{{foo.url}}" onerror="this.src='path/to/altimg.png'">
    
  • 3

    仅限HTML的解决方案,唯一的要求是您知道要插入的图像的大小 . 不适用于透明图像,因为它使用 background-image 作为填充 .

    我们可以成功使用 background-image 来链接在给定图像丢失时出现的图像 . 然后唯一的问题是破碎的图标图像 - 我们可以通过插入一个非常大的空字符来删除它,从而将内容推送到 img 的显示之外 .

    img {
      background-image: url("http://placehold.it/200x200");
      overflow: hidden;
    }
    
    img:before {
      content: " ";
      font-size: 1000px;
    }
    
    This image is missing:
    <img src="a.jpg" style="width: 200px; height: 200px"/>
    And is displaying the placeholder

    仅限CSS的解决方案(仅限Webkit)

    img:before {
      content: " ";
      background-image: url("http://placehold.it/200x200");
      display: block;
      width: 200px;
      height: 200px;
      position: relative;
      z-index: 0;
    }
    
    This image is there:
    <img src="http://placehold.it/100x100"/>
    This image is missing: <img src="a.jpg"/>
    And is displaying the placeholder

    或者,在jsfiddle:https://jsfiddle.net/xehndm3u/9/

  • 12

    一个简单的img元素不是很灵活,所以我把它与一个图片元素结合起来 . 这样就不需要CSS了 . 发生错误时,所有srcset都设置为回退版本 . 断开的链接图像未显示 . 它不会加载不需要的图像版本 . picture-element支持响应式设计和浏览器不支持的类型的多个回退 .

    <picture>
        <source id="s1" srcset="image1_not_supported_by_browser.webp" type="image/webp">
        <source id="s2" srcset="image2_broken_link.png" type="image/png">
        <img src="image3_fallback.jpg" alt="" onerror="this.onerror=null;document.getElementById('s1').srcset=document.getElementById('s2').srcset=this.src;">
    </picture>
    
  • 4

    无法确定将尝试查看您的页面的无数客户端(浏览器) . 需要考虑的一个方面是电子邮件客户端是事实上的网络浏览器,可能无法处理这种棘手的问题......

    因此,你应该包括一个带有DEFAULT WIDTH和HEIGHT的alt / text,就像这样 . 这是一个纯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 / text样式非常大...

    所以我的答案是使用带有很好的alt / text后备的Javascript .

    我也发现这很有趣:How to style an image's alt attribute

  • 247

    一个带有 JQuery 的可调版本,在你的结尾加上这个文件:

    <script>
        $(function() {
            $('img[data-src-error]').error(function() {
                var o = $(this);
                var errorSrc = o.attr('data-src-error');
    
                if (o.attr('src') != errorSrc) {
                    o.attr('src', errorSrc);
                }
            });
        });
    </script>
    

    并在您的 img 标签上:

    <img src="..." data-src-error="..." />
    
  • 0

    如果您使用的是Angular 1.x,则可以包含一个指令,允许您回退到任意数量的图像 . fallback属性支持单个url,数组内的多个url或使用范围数据的角度表达式:

    <img ng-src="myFirstImage.png" fallback="'fallback1.png'" />
    <img ng-src="myFirstImage.png" fallback="['fallback1.png', 'fallback2.png']" />
    <img ng-src="myFirstImage.png" fallback="myData.arrayOfImagesToFallbackTo" />
    

    向角度应用模块添加新的回退指令:

    angular.module('app.services', [])
        .directive('fallback', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var errorCount = 0;
    
                    // Hook the image element error event
                    angular.element(element).bind('error', function (err) {
                        var expressionFunc = $parse(attrs.fallback),
                            expressionResult,
                            imageUrl;
    
                        expressionResult = expressionFunc(scope);
    
                        if (typeof expressionResult === 'string') {
                            // The expression result is a string, use it as a url
                            imageUrl = expressionResult;
                        } else if (typeof expressionResult === 'object' && expressionResult instanceof Array) {
                            // The expression result is an array, grab an item from the array
                            // and use that as the image url
                            imageUrl = expressionResult[errorCount];
                        }
    
                        // Increment the error count so we can keep track
                        // of how many images we have tried
                        errorCount++;
                        angular.element(element).attr('src', imageUrl);
                    });
                }
            };
        }])
    
  • 1

    The above solution is incomplete ,它错过了属性 src .

    this.srcthis.attribute('src') 不相同,第一个包含对图像的完整引用,例如 http://my.host/error.jpg ,但该属性只保留原始值, error.jpg

    正确的解决方案

    <img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />
    
  • 1

    使用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");
        }
    });
    
  • 10

    对于任何图像,只需使用此JavaScript代码:

    if (ptImage.naturalWidth == 0)
        ptImage.src = '../../../../icons/blank.png';
    

    其中 ptImagedocument.getElementById() 获得的 <img> 标记地址 .

  • 0

    谷歌把这个页面扔到了“图像后备html”关键字,但由于上述情况并非如此,我正在寻找“低于9”的“svg后备支持”,我继续搜索,这就是我发现的:

    <img src="base-image.svg" alt="picture" />
    <!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->
    

    这可能是偏离主题的,但它解决了我自己的问题,也可能对其他人有所帮助 .

  • 14

    除了Patrick's精彩的答案,对于那些正在寻找跨平台角度js解决方案的人来说,在这里你去:

    <object type="image/png" data-ng-attr-data="{{ url || 'data:' }}">
        <!-- any html as a fallback -->
    </object>
    

    这是我试图找到正确解决方案的地方:http://plnkr.co/edit/nL6FQ6kMK33NJeW8DVDY?p=preview

  • 4

    好!!我发现这种方式很方便,检查图像的height属性为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');
      }
    

相关问题