一、事件對(duì)象
1、認(rèn)識(shí)事件對(duì)象
事件在瀏覽器中是以對(duì)象的形式存在的,即event。觸發(fā)一個(gè)事件,就會(huì)產(chǎn)生一個(gè)事件對(duì)象event,該對(duì)象包含著所有與事件有關(guān)的信息。包括導(dǎo)致事件的元素、事件的類型以及其他與特定事件相關(guān)的信息。
例如:鼠標(biāo)操作產(chǎn)生的event中會(huì)包含鼠標(biāo)位置的信息;鍵盤(pán)操作產(chǎn)生的event中會(huì)包含與按下的鍵有關(guān)的信息。
所有瀏覽器都支持event對(duì)象,但支持方式不同,在DOM中event對(duì)象必須作為唯一的參數(shù)傳給事件處理函數(shù),在IE中event是window對(duì)象的一個(gè)屬性。
2、html事件處理程序中event
<input id="btn" type="button" value="click" onclick=" console.log('html事件處理程序'+event.type)"/> 這樣會(huì)創(chuàng)建一個(gè)包含局部變量event的函數(shù)。可通過(guò)event直接訪問(wèn)事件對(duì)象。
3、DOM中的事件對(duì)象
DOM0級(jí)和DOM2級(jí)事件處理程序都會(huì)把event作為參數(shù)傳入。
<body><input id="btn" type="button" value="click"/><script>var btn=document.getElementById("btn");btn.onclick=function(event){console.log("DOM0 & click");console.log(event.type); //click}btn.addEventListener("click", function (event) {console.log("DOM2 & click");console.log(event.type); //click},false);</script></body> 4、IE中的事件對(duì)象
第一種情況: 通過(guò)DOM0級(jí)方法添加事件處理程序時(shí),event對(duì)象作為window對(duì)象的一個(gè)屬性存在。
<body><input id="btn" type="button" value="click"/><script>var btn=document.getElementById("btn");btn.onclick= function () {var event=window.event;console.log(event.type); //click}</script></body> 第二種情況:通過(guò)attachEvent()添加的事件處理程序,event對(duì)象作為參數(shù)傳入。
<body><input id="btn" type="button" value="click"/><script>var btn=document.getElementById("btn");btn.attachEvent("onclick", function (type) {console.log(event.type); //click})</script></body> 但是我有兩個(gè)地方不懂。
1、通過(guò)DOM0級(jí)方法添加的事件處理程序中同樣可以傳入一個(gè)event參數(shù),它的type和window.event.type一樣,但是傳入的event參數(shù)卻和window.event不一樣,為什么?
btn.onclick= function (event) {var event1=window.event;console.log('event1.type='+event1.type); //event1.type=clickconsole.log('event.type='+event.type); //event.type=clickconsole.log('event1==event?'+(event==event1)); //event1==event?false} 2、通過(guò)attachEvent添加的事件處理程序中傳入的event和window.event是不一樣的,為什么?
<body><input id="btn" type="button" value="click"/><script>var btn=document.getElementById("btn");btn.attachEvent("onclick", function (type) {console.log(event.type); //clickconsole.log("event==window.event?"+(event==window.event)); //event==window.event?false})</script></body> 以上所述是小編給大家介紹的JavaScript事件學(xué)習(xí)小結(jié)(三)js事件對(duì)象的相關(guān)知識(shí),希望對(duì)大家有所幫助,如果大家想了解更多內(nèi)容敬請(qǐng)關(guān)注VeVb武林網(wǎng)網(wǎng)站!



















