how to hide “image not found” icon on IE and chrom

2019-04-09 07:07发布

问题:

I have some images on my page.

By default if a given image is not available, then the broken image indicator is shown on Chrome and IE.

I want nothing to be shown but the alternative text in this case. Is there any way to handle it using CSS.

回答1:

using javascript

<img src="broken.png" onerror="this.style.display='none'"/>

edit: added small snipet that will handle all images.

$("img").error(function(){$(this).hide();});

example: http://jsfiddle.net/Va2Wd/



回答2:

Try setting alt=" " as an empty string, If the image isn't found, there will just be an empty space.



回答3:

You can use the onerror event in JavaScript to act when an image fails to load:

var img = document.getElementById("myImg");
img.onerror = function () { 
    this.style.display = "none";
}

or use

var images=document.getElementsByTagName("img");
for(i=0;img[i]!=null;i++)
{
img[i].style.display = "none";
}


回答4:

Instead of using JavaScript or CSS, you can use the object tag. It's cleaner and easier code. 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