Display alternate image

前端 未结 4 820
遇见更好的自我
遇见更好的自我 2021-01-04 01:02

Is it possible to show an alternate image if the original source file is not found? I would like to achieve this only with css and html, no javascript (or jQuery and alike).

相关标签:
4条回答
  • 2021-01-04 01:29

    yes, you can do it by using only html, when img src not found then it will throw error so here we can handle it. One more point is set this.onerror = null for recursive calling (default image not found)

    <img alt="User Image" class="user-image" src="/Resources/images/user-icon.png" onerror="this.onerror=null; this.src='/Resources/images/user-icon.png'">
    
    0 讨论(0)
  • 2021-01-04 01:33
    <object data="foobar.png" width=200 height=200>
      <img src="test.png" alt="Just testing.">
    </object>
    

    Here foobar.png is the primary image, test.png is the fallback image. By the semantics of the object element, the content of the element (here the img element) should be rendered if and only if the primary data (specified by the data attribute) cannot be used.

    Though browsers have had awful bugs in implementations of object in the past year, this simple technique seems to work on modern versions of IE, Firefox, Chrome.

    0 讨论(0)
  • 2021-01-04 01:42

    You can do this using the CSS background-image property of the img element, i.e.

    img
    {
    background-image:url('default.png');
    }
    

    However, you have to give a width or height for this to work (when the img-src is not found):

    img
    {
    background-image:url('default.png');
    width:400px;
    }
    
    0 讨论(0)
  • 2021-01-04 01:49

    Very simple and best way to achieve this with little code

    <img class="avatar" src="img/one.jpg" alt="Not Found" onerror=this.src="img/undefined.jpg">
    

    To me the above works perfect!

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