JavaScript添加IE事件處理常式

來源:互聯網
上載者:User

標籤:事件綁定   script   get   asc   檢測   move   seo   匿名   位置   

  IE和其他主流的瀏覽器之間有很多的不相容,有一些其他瀏覽器支援的方法在IE中並不能完美的支援,首先哪些支援呢?

    1、直接在HTML代碼的元素屬性的位置為事件綁定處理常式;

    2、使用JavaScript的 node.onclick=function(){}

  IE8及之前的版本不支援addEventListener和removeEventListener,支援的是attachEvent()和detachEvent()

    attachEvent()和detachEvent()都需要兩個參數:

    第一個參數是要綁定的事件(onclick、onmouseover.....注意和addEventListener不同)

    第二個參數是要綁定的處理常式(匿名函數或者函數名,注意如果不是匿名函數,函數名不要加括弧)

  在使用addEventListener之前應該先檢測當前瀏覽器是否支援該方法,可以將代碼封裝到一個對象中:

<button id="btn">按鈕</button><script>var eventUtil = {//type 傳入 click mouseover,而不傳onclick,mouseoveraddEvent : function(element, type, func){if (element.addEventListener) {    //所有主流瀏覽器,除了 IE 8 及更早 IE版本    element.addEventListener(type, func, false);} else if(element.attachEvent) {  // IE 8 及更早 IE 版本    element.attachEvent(‘on‘+type, func);} else {var type = "on"+type;//element.type = func; //wrong,不會成功element[type] = func;}},removeEvent : function(element, type, func){if (element.removeEventListener) {    //所有主流瀏覽器,除了 IE 8 及更早 IE版本    element.removeEventListener(type, func, false);} else if(element.detachEvent) {  // IE 8 及更早 IE 版本    element.detachEvent(‘on‘+type, func);} else {var type = "on"+type;//element.type = null; //wrong,不會成功element[type] = null;}}}var btn = document.getElementById("btn");function showOne(){ alert("one"); }eventUtil.addEvent(btn, "click", showOne);eventUtil.removeEvent(btn, "click", showOne);</script>

  

  

JavaScript添加IE事件處理常式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.