JavaScript uses onerror to set the default image display instead of alt and javascriptonerror.
JavaScript code
// Processing function errorImg (img) {img. src = "img .jpg"; img. onerror = null ;}
Html code
For the sake of beauty, when the webpage image does not exist, the cross image is not displayed
When displayed on the page, if the image is moved or lost, an image with X will be displayed on the page, which affects the user experience. Even if the "image XX" prompt is displayed using the alt attribute, it does not play much role.
In fact, it can be handled as follows: when the image does not exist, the onerror event will be triggered. We can do some remedial work in this event, for example:
1. Hide the image element:
For the sake of beauty, when the webpage image does not exist, do not display the cross image src = "image url address" alt = "image XX" onerror = "this. style. display = 'none'"/>
2. Replace with the default image:
For the sake of beauty, when the webpage image does not exist, do not display the cross image src = "image url address" alt = "image XX" onerror = "this. src = 'default image url address' "/>
Note: improper use may lead to an endless loop in the IE kernel browser. For example, if the [url address of the default image] fails to be loaded (for example, when the network speed is slow) or does not exist, it will be loaded repeatedly, resulting in a stack overflow error.
Therefore, the following two solutions are required:
A. Change the onerror code to another processing method or make sure that the default image in onerror is small enough and exists.
B. Control the onerror event to be triggered only once. Add this sentence: this. onerror = null; Add the following statement:
For the sake of beauty, when the webpage image does not exist, do not display the cross image src = "image url address" alt = "image XX" onerror = "this. src = 'default image url; this. onerror = null' "/>
After testing, the above method is supported in various IE versions and Google and Firefox browsers.
Articles you may be interested in:
- Onerror usage in img labels
- Js pay attention to the onerror event analysis of img Images
- The onerror event Stack overflow at line: 0 is not found in the img image parsing.
- JS optimized the img label and used onerror to display the default image.