Home  >  Article  >  Web Front-end  >  js dynamically adds onload, onresize, onscroll events (alternative method)_javascript skills

js dynamically adds onload, onresize, onscroll events (alternative method)_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:45:201023browse

The onload, onresize, and onscroll events of window are different from other events. They cannot be added using attachEvent or addEventListener.

In other words, it can only come like this (take onload as an example, the same below):

Copy code The code is as follows:

window.onload = function()
{
// ...
};

But there is The problem is that when you want to add a new event handler for onload, you cannot directly assign a value to window.onload, otherwise the previous assignment will be overwritten.

You can do this:
Copy the code The code is as follows:

var oldLoadHandler = window.onload;
window.onload = function()
{
if (oldLoadHandler)
{
oldLoadHandler();
}
newLoadHandler();
};

In ezj, it is more convenient.
Copy code The code is as follows:

$(window).ready(onloadHandler1);
$(window).ready(onloadHandler2);


Explanation
The onload event we usually come into contact with is document.body.onload, but this is actually It is due to IE's misunderstanding. The correct one should be window.onload. window.onload is valid in IE, Firefox, and Chrome.
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