JS事件流,事件綁定

事件流,事件綁定

 

主流browser,符合W3C標準,支持冒泡和捕獲

低版本ie,僅支持冒泡

冒泡到

window

document

事件綁定/解綁

elem.addEventListener(evt, func, useCapture)

elem.removeEventListener(evt, func)

elem.attachEvent(onevt, func)

elem.detachEvent(onevt, func)

阻止事件流

e.stopPropagation() //阻止傳播(捕獲+冒泡)

(部分也兼容了ie)

window.event.cancelBubble //阻止冒泡

阻止默認事件

e.preventDefault()

window.event.returnValue = false

 

DOM2級事件事件流:

       三個階段:捕獲、處於、冒泡

 

document.getElementById('daddy').addEventListener('click',function(){console.log('daddy')}, true); //捕獲階段觸發
document.getElementById('child').addEventListener('click',function(e){console.log('child')}, false); //冒泡階段觸發
document.getElementById('grandchild ').addEventListener('click',function(){console.log('grandchild ')}, true); //捕獲階段觸發

輸出:daddy, grandchild, child;

 

target, currentTarget和this

舉個栗子就好明白了

document.getElementById('parentNode').addEventListener('click',function(e){
       var t1 = e.target //實際觸發事件的對象, childNode
       var t2 = e.currentTarget //綁定事件的對象, parentNode
       var t3 = this; //一般情況下===currentTarget, 此case下爲obj
}.bind(obj))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章