javascript 在javascript中检测损坏图像的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3495260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Way to detect broken images in javascript?
提问by Rod Johnson
I need to be able to detect if an image is broken and replace with a default image if the image link is broken. I know i could do this with an image proxy, but was hoping to do it on the fly with javascript.
我需要能够检测图像是否损坏并在图像链接损坏时替换为默认图像。我知道我可以用图像代理来做到这一点,但希望能用 javascript 即时做到这一点。
回答by meder omuraliev
I believe it's the onerrorevent of the imgelement. onerror=function(){}though i've never used it.
我相信这onerror是img元素的事件。onerror=function(){}虽然我从来没有用过。
回答by mhitza
As any event the onerrorwill propagate upwards on the DOM, so you could make a generic handler for this type of errors.
任何事件onerror都将在 DOM 上向上传播,因此您可以为此类错误创建通用处理程序。
<script type="text/javascript">
jQuery(document).bind('error', function(event) {
console.log(event.target.src);
});
</script>
回答by Robert
You can use <img onerror='doWhateverFunction()'etc etc
您可以使用<img onerror='doWhateverFunction()'等
http://msdn.microsoft.com/en-us/library/cc197053(v=VS.85).aspx
http://msdn.microsoft.com/en-us/library/cc197053(v=VS.85).aspx
回答by Hyman B Nimble
Example of code:
代码示例:
<script language='javascript'>
function defaultImage(img)
{
img.onerror = "";
img.src = 'default.gif';
}
</script>
<img alt="My Image" src="someimage.gif" onerror="defaultImage(this);" />

