- 事件冒泡
- 取消事件冒泡 e.cancelBubble = true
- 例子:仿select控件
- 事件捕獲
- 非標(biāo)準(zhǔn)下IE是沒有的,在綁定事件中,標(biāo)準(zhǔn)是有的。
冒泡概述
簡單來說:父元素有自己的點擊方法。子元素也有自己的點擊方法或者子元素就不想執(zhí)行父元素的方法.
這樣我們就必須阻止冒泡。
阻止冒泡
讓父元素執(zhí)行父元素的方法,讓子元素執(zhí)行子元素的方法.
<body>
<style>
*{margin:0px;padding:0px;}
.div1{background:red;width:400px;height:400px;margin:0 auto;}
.div2{background:blue;width:200px;height:200px;margin:0 auto;}
</style>
<div class="div1">
<div class="div2">
測試冒泡
</div>
</div>
</body>
<script>
document.getElementsByClassName("div1")[0].onclick = function(){
window.alert("彈出最外層");
}
document.getElementsByClassName("div2")[0].onclick = function(e){
e.cancelBubble = true;
window.alert("彈出最內(nèi)層");
}
</script>
e.cancelBubble=true;這樣就阻止冒泡了.
給事件綁定的第二種形式
可以用addEventListener也可以用attachEvent看IE還是谷歌,用的不多
call方法
call方法可以傳遞2個參數(shù),第一個參數(shù)可以改變函數(shù)的this.第二個參數(shù)開始就是原來函數(shù)的參數(shù)列表
如果call方法傳入的第一個參數(shù)是null,那就不改變函數(shù)內(nèi)部this指向.
call方法的核心就是第一個參數(shù),改變this指向
function fn1(){
window.alert(this);
}
fn1(); //彈出來window
fn1.call() ;//等價于fn1();彈出的結(jié)果window
fn1.call(1); //彈出來1 改變了this
事件綁定的取消
- document.oncllick = null;
- IE:obj.detachEvent(事件名稱,事件函數(shù))
標(biāo)準(zhǔn):obj.removeEventListenrt(事件名稱,時間函數(shù),是否捕獲)