Inputting a default image in case the src attribute of an html

后端 未结 22 2451
渐次进展
渐次进展 2020-11-22 16:02

Is there any way to render a default image in an HTML tag, in case the src attribute is invalid (using only HTML)? If not, what would

22条回答
  •  旧时难觅i
    2020-11-22 16:35

    I don't think it is possible using just HTML. However using javascript this should be doable. Bassicly we loop over each image, test if it is complete and if it's naturalWidth is zero then that means that it not found. Here is the code:

    fixBrokenImages = function( url ){
        var img = document.getElementsByTagName('img');
        var i=0, l=img.length;
        for(;i

    Use it like this:

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

    Tested in Chrome and Firefox

提交回复
热议问题