How to hide image broken Icon using only CSS/HTML?

前端 未结 17 1561
不思量自难忘°
不思量自难忘° 2020-11-27 09:14

How can I hide the broken image icon? Example: \"Example\"

I have an image with error src:

相关标签:
17条回答
  • 2020-11-27 09:58

    The trick with img::after is a good stuff, but has at least 2 downsides:

    1. not supported by all browsers (e.g. doesn't work on Edge https://codepen.io/dsheiko/pen/VgYErm)
    2. you cannot simply hide the image, you cover it - so not that helpful when you what to show a default image in the case

    I do not know an universal solution without JavaScript, but for Firefox only there is a nice one:

    img:-moz-broken{
      opacity: 0;
    }
    
    0 讨论(0)
  • 2020-11-27 10:00

    Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead you may want to replace that with a "missing image" graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible, because images that a browser can't find fire off an "error" JavaScript event we can watch for.

        //Replace source
        $('img').error(function(){
                $(this).attr('src', 'missing.png');
        });
    
       //Or, hide them
       $("img").error(function(){
               $(this).hide();
       });
    

    Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.

    0 讨论(0)
  • 2020-11-27 10:01

    in case you like to keep/need the image as a placeholder, you could change the opacity to 0 with an onerror and some CSS to set the image size. This way you will not see the broken link, but the page loads as normal.

    <img src="<your-image-link->" onerror="this.style.opacity='0'" />
    
    img {
        width: 75px;
        height: 100px;
    }
    
    0 讨论(0)
  • 2020-11-27 10:01

    Use the object tag. Add alternative text between the tags like this:

    <object data="img/failedToLoad.png" type="image/png">Alternative Text</object>
    

    http://www.w3schools.com/tags/tag_object.asp

    0 讨论(0)
  • 2020-11-27 10:05

    A basic and very simple way of doing this without any code required would be to just provide an empty alt statement. The browser will then return the image as blank. It would look just like if the image isn't there.

    Example:

    <img class="img_gal" alt="" src="awesome.jpg">
    

    Try it out to see! ;)

    0 讨论(0)
提交回复
热议问题