Home  >  Article  >  Web Front-end  >  js动态添加onload、onresize、onscroll事件(另类方法)_javascript技巧

js动态添加onload、onresize、onscroll事件(另类方法)_javascript技巧

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

window 的 onload、onresize、onscroll 事件,跟其他的事件不一样,它不能用 attachEvent 或 addEventListener 来添加。

也就是说,它只能这样来(以 onload 为例,下同):

复制代码 代码如下:

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

但这有个问题,就是想再为 onload 增加新的事件处理程序时,不能直接为 window.onload 赋值了,否则前面的赋值就会被覆盖了。

可这样做
复制代码 代码如下:

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

在 ezj 中,就更加方便了。
复制代码 代码如下:

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


说明
我们一般接触的 onload 事件是 document.body.onload,但这实际上是由于 IE 的误导,正确的应该是 window.onload,window.onload 在 IE、Firefox、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