javaScript事件(三)事件對象

來源:互聯網
上載者:User

javaScript事件(三)事件對象
1、認識事件對象 事件在瀏覽器中是以對象的形式存在的,即event。觸發一個事件,就會產生一個事件對象event,該對象包含著所有與事件有關的資訊。包括導致事件的元素、事件的類型以及其他與特定事件相關的資訊。 例如:滑鼠操作產生的event中會包含滑鼠位置的資訊;鍵盤操作產生的event中會包含與按下的鍵有關的資訊。 所有瀏覽器都支援event對象,但支援方式不同,在DOM中event對象必須作為唯一的參數傳給事件處理函數,在IE中event是window對象的一個屬性。 2、html事件處理常式中event <input id="btn" type="button" value="click" onclick=" console.log('html事件處理常式'+event.type)"/>這樣會建立一個包含局部變數event的函數。可通過event直接存取事件對象。 3、DOM中的事件對象 DOM0級和DOM2級事件處理常式都會把event作為參數傳入。 複製代碼<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中的事件對象 第一種情況: 通過DOM0級方法添加事件處理常式時,event對象作為window對象的一個屬性存在。 複製代碼<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>複製代碼第二種情況:通過attachEvent()添加的事件處理常式,event對象作為參數傳入。 複製代碼<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>複製代碼  但是我有兩個地方不懂。 1、通過DOM0級方法添加的事件處理常式中同樣可以傳入一個event參數,它的type和window.event.type一樣,但是傳入的event參數卻和window.event不一樣,為什嗎?     btn.onclick= function (event) {        var event1=window.event;        console.log('event1.type='+event1.type);  //event1.type=click        console.log('event.type='+event.type);    //event.type=click        console.log('event1==event?'+(event==event1));  //event1==event?false    }2、通過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);    //click        console.log("event==window.event?"+(event==window.event)); //event==window.event?false    })</script></body>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.