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

img onload event binding can be executed by all browsers_Basic knowledge

WBOY
Release: 2016-05-16 17:46:01
Original
1259 people have browsed it

When you need to bind the onload event of img, generally everyone will think of using the conventional method to bind the event, as follows:

Copy code The code is as follows:





img onload event binding (wrong usage)
< script type='text/javascript'>
window.onload = function(){
var img = document.getElementById('imgId');
img.onload = function(){
alert(1);
};
};







At this time, you will find that alert(1) is not executed. What is the reason? Especially under ie and ff browsers.
And when using the jquery plug-in library, you will find that alert does not pop up in IE and Opera browsers, but it pops up in other browsers. Why is this? !
Mainly the window.onload event is executed after the page dom element is loaded, which also includes the completion of the src loading in the img image. Then img.onload will not be executed,
because it is monitoring whether the src of img is loaded.
So, how to bind the onload event to the img image? The specific code is as follows:
Copy code The code is as follows:




img onload event binding (correct usage)







This method executes alert(1) in every browser.
That is, after the dom element of the page is loaded, obtain the dom object of img, obtain its src attribute, then set its src to '' empty, then listen to the onload event of img, and finally set the src attribute of img. .
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