Home >Web Front-end >JS Tutorial >JS optimizes the img tag and uses onerror to display the default image

JS optimizes the img tag and uses onerror to display the default image

高洛峰
高洛峰Original
2017-02-04 13:15:431301browse

There are many reasons why website images are not displayed, such as network problems, file itself problems, file URL problems, etc. When the image fails to load, the onerror event will be triggered. We can use this to effectively avoid image loading failure. Awkward!

js code

//图像加载出错时的处理 
function errorImg(img) { 
img.src = "http://static.xuexiba.com/uploadfile//UserInfo/Avatar/201403/1303992393385832875324.jpg"; 
img.onerror = null; 
}

html code

<img     style="max-width:90%"  style="max-width:90%" src="1.jpg" onerror="errorImg(this)" / alt="JS optimizes the img tag and uses onerror to display the default image" >

Page effect

JS optimizes the img tag and uses onerror to display the default image

More JS optimizes the use of img tags Onerror displays the default image. For related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn