首頁  >  文章  >  web前端  >  如何在 Internet Explorer 9 中使用「addEventListener」方法?

如何在 Internet Explorer 9 中使用「addEventListener」方法?

Linda Hamilton
Linda Hamilton原創
2024-10-27 21:37:01612瀏覽

How Do I Use the

將addEventListener 合併到Internet Explorer

問題:

在Internet Explorer 9 中進行事件處理時,什麼是相當於Element 物件的addEventListener 方法?

答案:

Internet Explorer 9 引入了標準化的 addEventListener 方法,該方法被普遍採用作為處理事件的首選技術Web 開發。

Internet Explorer 的舊版事件處理

在 Internet Explorer 9 之前,Internet Explorer 使用非標準的 AttachEvent 方法而不是 addEventListener。以下是其工作原理的範例:

elem.attachEvent("on" + evnt, func);

統一跨瀏覽器的事件處理

要建立跨瀏覽器相容的事件處理函數,可以使用以下方法使用:

function addEvent(evnt, elem, func) {
  if (elem.addEventListener)  // W3C DOM
    elem.addEventListener(evnt, func, false);
  else if (elem.attachEvent) { // IE DOM
    elem.attachEvent("on" + evnt, func);
  }
  else { // No much to do
    elem["on" + evnt] = func;
  }
}

函數有效地將所需的事件(evnt)、元素(elem)和要執行的函數(func)轉換為跨瀏覽器相容的事件處理實作。

以上是如何在 Internet Explorer 9 中使用「addEventListener」方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn