Home > Article > Web Front-end > JavaScript sets default image display by using onerror instead of alt_javascript trick
JavaScript code
//图像加载出错时的处理 function errorImg(img) { img.src = "默认图片.jpg"; img.onerror = null; }
html code
<img width="32" height="32" src="1.jpg" onerror="errorImg(this)" />
For the sake of beauty, the cross picture will not be displayed when the web page picture does not exist
When it is When the page is displayed, if the image is moved or lost, an image with an X will be displayed on the page, which greatly affects the user experience. Even if the alt attribute is used to give a prompt message of "Picture XX", it will not have much effect.
In fact, it can be handled like this: when the picture does not exist, the onerror event will be triggered. We can do some remedial work in this event, such as:
1. Let Hide this picture element:
为了美观当网页图片不存在时不显示叉叉图片 src="图片的url地址" alt="图片XX" onerror="this.style.display='none'"/>
2. Replace it with the default picture:
为了美观当网页图片不存在时不显示叉叉图片 src="图片的url地址" alt="图片XX" onerror="this.src='默认图片的url地址'"/>
Note: If used improperly, it will cause an infinite loop in IE-based browsers. For example: When the [url address of the default image] fails to load (for example, when the network speed is relatively slow) or does not exist, it will be loaded repeatedly, eventually causing a stack overflow error.
Therefore, the following two methods need to be used to solve the problem:
a. Change the onerror code to other processing methods or ensure that the default image in onerror is small enough and exists.
b. To control the onerror event to be triggered only once, you need to add this sentence: this.onerror=null; after adding it, it will be as follows:
为了美观当网页图片不存在时不显示叉叉图片 src="图片的url地址" alt="图片XX" onerror="this.src='默认图片的url地址;this.onerror=null'"/>
After testing, the above method is supported in all versions of IE and Google and Firefox browsers.
The above is how JavaScript uses onerror to set the default image display instead of the alt_javascript technique. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!