Home > Web Front-end > JS Tutorial > body text

JavaScript sets default image display by using onerror instead of alt_javascript trick

PHP中文网
Release: 2016-05-16 15:12:59
Original
1523 people have browsed it

JavaScript code

 //图像加载出错时的处理
function errorImg(img) {
img.src = "默认图片.jpg";
img.onerror = null;
}
Copy after login

html code

<img width="32" height="32" src="1.jpg" onerror="errorImg(this)" />
Copy after login

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=&#39;none&#39;"/>
Copy after login

2. Replace it with the default picture:

为了美观当网页图片不存在时不显示叉叉图片 src="图片的url地址" alt="图片XX" 
onerror="this.src=&#39;默认图片的url地址&#39;"/>
Copy after login

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=&#39;默认图片的url地址;this.onerror=null&#39;"/>
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template