FireFox和Safari兼容event.path

在項目開發中遇到需要獲取觸發事件元素冒泡過程的所有元素,在Chrome中可以通過event.path獲取。

element.onClick(event) {
  const ev = window.event || event;
  const path = ev.path;
}

該屬性在Chrome和Opera瀏覽器下沒問題,但是在Firefox和Safari中發現event並沒有path屬性。 進過查找資料發現,在瀏覽器新的標準裏定義的composedPath可以獲取

element.onClick(event) {
  const ev = window.event || event;
  const path = event.path || (event.composedPath && event.composedPath());
  console.log(path)  //[button#btn, div, body, html, document, Window]
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章