`
wfsheep
  • 浏览: 15804 次
文章分类
社区版块
存档分类
最新评论

onload事件和window,document,body的研究

阅读更多

今天在工作中用到了onload事件,发现了一些有趣的事情,比如一般来说,如果我们需要给一个DOM结构绑定一个事件,我们一般会采用如下方法(以Window对象为例):

【现象】

	window.onload = function() {
		console.log('<span style="font-family: Arial, Helvetica, sans-serif;">window.onload</span><span style="font-family: Arial, Helvetica, sans-serif;">');</span>
	};
   
        window.addEventListener && window.addEventListener("load", function() {
		console.log('window.addEvent');
	});
执行这两个方法,可以看到如下截图:


说明,这两个方法都被触发了,在这一点上IE表现也是一致的。

接下来我们来试试document对象

	document.onload = function() {
		console.log('document.onload');
	};
   
        window.addEventListener && document.addEventListener("load", function() {
		console.log('<span style="font-family:Arial, Helvetica, sans-serif;">document</span>.addEvent');
	});
	
	window.attachEvent && document.attachEvent('onload', function() {
		console.log('document.attachEvent');
	});
执行后发现,document的onload事件无论是哪种方式都不会触发。


再接下来,我们来试试body对象

	document.body.onload = function() {
		console.log('body.onload');
	};
	
	window.addEventListener && document.body.addEventListener("load", function() {
		console.log('body.addEvent');
	});
	
	window.attachEvent && document.body.attachEvent('onload', function() {
		console.log('body.attachEvent');
	});
结果如下图:


可以看到,说明通过这种写法只有onload方式绑定的被触发了。

还有更好玩的,当同时给body和window使用onload方法时,只有window的onload方法触发

具体代码如下:

	document.body.onload = function() {
		console.log('body.onload');
	};
	
	window.onload = function() {
		console.log('window.onload');
	}
执行结果如:


【结论】

所以总结如下:
1、onload和addEventListener当使用在window上的时候都触发

2、当使用在document时,都不触发

3、当使用在body上时,只有onload触发

4、当body和window同时使用onload方法时,body的方法会被吃掉。


【深入研究】

这里的研究主要是参看了w3c草案中的一些说明,怕翻译不好,贴出原文,貌似load事件和其他的有很多不同,

6.1.6.3Event firing

Certain operations and methods are defined as firing events on elements. For example, theclick()method on theHTMLElementinterface is defined as firing aclickevent on the element.[DOMEVENTS]

Firing a simple event namedemeans that an event with the namee, which does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and which uses theEventinterface, must be dispatched at the given target.

Firing a synthetic mouse event namedemeans that an event with the namee, which does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated), and which uses theMouseEventinterface, must be dispatched at the given target. The event object must have itsscreenX,screenY,clientX,clientY, andbuttonattributes set to 0, itsctrlKey,shiftKey,altKey, andmetaKeyattributes set according to the current state of the key input device, if any (false for any keys that are not available), itsdetailattribute set to 1, and itsrelatedTargetattribute set to null. ThegetModifierState()method on the object must return values appropriately describing the state of the key input device at the time the event is created.

Firing aclickeventmeansfiring a synthetic mouse event namedclick, which bubbles and is cancelable.

The default action of these events is to do nothing except where otherwise stated.

6.1.6.4Events and theWindowobject

When an event is dispatched at a DOM node in aDocumentin abrowsing context, if the event is not aloadevent, the user agent must also dispatch the event to theWindow, as follows:

  1. In the capture phase, the event must propagate to theWindowobject before propagating to any of the nodes, as if theWindowobject was the parent of theDocumentin the dispatch chain.
  2. In the bubble phase, the event must propagate up to theWindowobject at the end of the phase, unless bubbling has been prevented, again as if theWindowobject was the parent of theDocumentin the dispatch chain

另外就是,在第6.1.6.2节中有详细描述window,document,body对象对各事件的支持,因为太长,就不贴出来了。


Ps:本文纯属个人研究,如有谬误,烦请指出,万分感谢。


分享到:
评论

相关推荐

    获取页面长宽和滚动条的位置

    &lt;!... function GetPageSize() { var scrW, scrH; if(window.innerHeight && window.scrollMaxY) ... scrW = window.innerWidth + window.scrollMaxX;...&lt;body onload="main();"&gt; &lt;/body&gt; &lt;/html&gt;

    利用 window_onload 实现select默认选择

    请参考这个程序: &lt;?... ?&gt; &lt;... &lt;head&gt; &lt;... charset=gb2312"&gt;...meta name="GENERATOR" content="Microsoft FrontPage 4.0"&gt;...meta name="ProgId" content="FrontPage....body onload="window.form1.day.

    窗口和表单事件.pptx

    1.1 ready事件 VS onload事件 1、窗口事件-resize事件 1.2 resize 事件 当调整浏览器窗口大小时,发生 resize 事件。 x=0; $(document).ready(function(){ $(window).resize(function(){ $("span").text(x+=1); });...

    window.addEventListener来解决让一个js事件执行多个函数

    可能你也碰到过这种情况,就是在js的代码中用了[removed]后,可能会影响到body中的onload事件。你可以全写在body中,也可以全放到[removed]中,但是这样并不是很方便,有时我们需要两个同时用到。这时就要用window....

    JQuery下关于$.Ready()的分析

    对于Body的Onload事件和JQuery的Ready方法相比,有很多弊端.比如: 1.加载多个函数的问题 &lt;body onload=”a();b();”&gt; &lt;/body&gt; 在Onload事件中只能这样加载,很丑陋…而在JQuery中你可以利用多个JQuery....

    JQuery Tips相关(1)—-关于$.Ready()

     对于Body的Onload事件和JQuery的Ready方法相比,有很多弊端.比如: 1.加载多个函数的问题 &lt;body onload="a();b();"&gt; &lt;/body&gt;  在Onload事件中只能这样加载,很丑陋…而在JQuer

    页面中body onload 和 [removed] 冲突的问题的解决

    1.使用attachEvent给onload添加所需运行的函数 代码如下:if (document.all) { window.attachEvent(‘onload’, FuncName) } else { window.addEventListener(‘load’, FuncName, false); } 2.使用[removed] = ...

    javascript小技巧

    document.all.topmsg.style.left=document.body.scrollLeft+document.body.clientWidth/2-document.all.topmsg.offsetWidth/2 document.all.topmsg.style.top=document.body.scrollTop+document.body.clientHeight-...

    Web前端开发工程师笔试题及答案

    腾迅Web前端开发工程师笔试题及答案 ...function elementName(evt){ evt = evt|| window.event; // IE: window.event ... var el = document.getElementsByTagName('body'); el[0].onclick = elementName; } ......

    javaScript常用事件

    2.onLoad页面加载事件:当页面加载时,自动调用函数(方法)。注意:此方法只能写在&lt;body&gt;标签之中! 3.onScroll窗口滚动事件:当页面滚动时调用函数。注意:此事件写在方法的外面,且函数名(方法名)后不加括号!...

    js 实现飘动土层代码

    ; z-index: 2; left: 87px; top: 16px; width: 115px; height: 91px"&gt;...&lt;SCRIPT event=onload for=window language=JavaScript&gt; //pagestart(); &lt;/SCRIPT&gt;

    javascript函数的解释

    68.JS中分为两种窗体输出:模态和非模态.window.showModaldialog(),window.showModeless() 69.状态栏文字的设置:window.status='文字',默认的状态栏文字设置:window.defaultStatus = '文字.'; 70.添加到收藏夹:...

    js使用小技巧

    &lt;body onload="window.resizeTo(window.screen.width - 4,window.screen.height-50);window.moveTo(-4,-4)"&gt; 无关闭按钮IE window.open("aa.htm", "meizz", "fullscreen=7"); 统一编码/解码 alert...

    各种浏览器兼容问题

    [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]在IE、Opera均正常有效,唯独FF既不执行,也不报错,因为在FF,document.body.onload是undefined(未定义),把一个函数赋值给undefined既不会发生什么事情,也不算...

    jqzoom放大镜插件.zip

    this.node.onload = function() { //setto il cursor e la posizione dell'href a.css({'cursor':'crosshair','display':'block'}); if(a.css('position')!= 'absolute' && a.parent().css('position')) { ...

    利用WebBrowser彻底解决Web打印问题(包括后台打印)

    doc.write("&lt;body onload=\"parent.onprintHiddenFrame()\"&gt;");doc.write("&lt;iframe name=printMe width=0 height=0 src=\"" +url + "\"&gt;&lt;/iframe&gt;");doc.write("&lt;/body&gt;");doc.close();}function onprintHiddenFrame...

    【JavaScript源代码】JavaScript 鼠标事件(MouseEvent)案例讲解.docx

    JavaScript 鼠标事件(MouseEvent)案例讲解  鼠标事件-MouseEvent 当鼠标进行某种... console.log(e) } window.onload = function (){ document.getElementsByTagName('body')[0].addEventListener('mousedown',mo

    107个常用javascript语句

    68.JS中分为两种窗体输出:模態和非模態.window.showModaldialog(),window.showModeless() 69.状態栏文字的设置:window.status='文字',默认的状態栏文字设置:window.defaultStatus = '文字.'; 70.添加到收藏夹:...

    跟随鼠标的时钟 js特效

    &lt;title&gt;hsdj &lt;BODY text=#000000 bgColor=#000000&gt; &lt;!-- dCol="0000FF" fCol="FF0000" sCol="00FF00" ...d=new Array("星期日","星期一","星期二","星期三",...window.onMouseMove=Mouse:document.onmousemove=Mouse; ...

    很酷的时钟 (跟随鼠标飘动的双层时钟!).

    Oh.style.top=window.document.body.scrollTop; Om.style.top=window.document.body.scrollTop; Os.style.top=window.document.body.scrollTop; } for (i=0; i ; i++){ var F=(ns)?document.layers['nsFace'+i]:...

Global site tag (gtag.js) - Google Analytics