一、基本概念:DOM事件級(jí)別
DOM0級(jí):
element.onclick=function(event){}
DOM2級(jí):element.addEventListener('click',function(event){},false)
冒泡
DOM3級(jí):element.addEventListener('keyup',function(event){},false)
,新增的鼠標(biāo)鍵盤事件
注意dom1級(jí)沒有涉及事件杰刽,不是沒有dom1標(biāo)準(zhǔn)
二、事件模型
事件模型
指捕獲和冒泡
三全释、事件流
捕獲階段的事件流
冒泡階段反之
事件處于捕獲階段觸發(fā)
ev.addEventListener('click', function (e) {
console.log('ev captrue');
}, true);
window.addEventListener('click', function (e) {
console.log('window captrue');
}, true);
document.addEventListener('click', function (e) {
console.log('document captrue');
}, true);
document.documentElement.addEventListener('click', function (e) {
console.log('html captrue');
}, true);
document.body.addEventListener('click', function (e) {
console.log('body captrue');
}, true);
四辅辩、Event對(duì)象常見應(yīng)用
-
event.preventDefault()
:取消事件的默認(rèn)行為颤陶,a標(biāo)簽設(shè)置此方法,不會(huì)打開連接 -
event.stopPropagation()
:取消事件冒泡或捕獲穴亏。 -
event.stopImmediatePropagation()
:取消事件冒泡或捕獲蜂挪,同時(shí)取消其他事件處理程序的調(diào)用。
僅打印click1
window.addEventListener('click',function(e){
console.log('click1')
e.stopImmediatePropagation()
},true)
window.addEventListener('click',function(e){
console.log('click2')
},true)
-
event.currentTarget:
范圍大嗓化,表示添加事件處理程序的那個(gè)元素 -
event.target:
小范圍棠涮,表示真正點(diǎn)擊的目標(biāo)元素
五、自定義事件
無參數(shù)
var eve = new Event('test');//定義test事件
ev.addEventListener('test', function () {
console.log('test dispatch');
});
setTimeout(function () {//1s后出發(fā)事件
ev.dispatchEvent(eve);
}, 1000);
var f=document.getElementById('float')
var newE=document.createEvent('Event')//創(chuàng)建新事件
newE.initEvent('a')//初始化事件類型
f.addEventListener('a',function(e){
console.log(5)
})
setTimeout(function () {//1s后出發(fā)事件
f.dispatchEvent(newE)
}, 1000);
有參數(shù)
var newE=document.createEvent('CustomEvent')
newE.initCustomEvent('a',true,false,'hello')//事件類 型‘a(chǎn)’,冒泡刺覆,事件不可以取消严肪,detail中的值為hello
f.addEventListener('a',function(e){
console.log(e.detail)
})
f.dispatchEvent(newE)
六、IE事件與DOM事件的區(qū)別
1谦屑、DOM中事件的this指向當(dāng)前元素驳糯,而IE中的this指向window
DOM
var f=document.getElementById('float')
f.addEventListener('click',function(e){
console.log(this===f)//true
},true)
f.onclick=function(e){
console.log(this===f)//true
}
IEEdge已經(jīng)不支持attachEvent了
f.attachEvent('onclick',function(){
console.log(this===window)//true
})
2、IE中的同一事件類型的不同處理程序氢橙,按照反添加順序執(zhí)行酝枢,DOM反之。
3悍手、事件對(duì)象不同
DOM級(jí)別的事件處理程序均會(huì)傳入event對(duì)象帘睦,在IE中的event對(duì)象方式取決于指定的事件處理程序方法袍患。
IE中使用DOM0方法,event對(duì)象是window的一個(gè)屬性
f.onclick=function(){
event=window.event
console.log(this===f)//true
}
IE中使用attachEvent()方法,會(huì)傳入event對(duì)象,同DOM
f.attachEvent('onclick',function(event){
console.log(event.type)
})
4、IE中的事件目標(biāo)是srcElement
event.srcElement
,window.event.srcElement