ITPUB老博客搬迁至此
首先我们还得了解:
事件对象:事件发生时系统自动产生的对象,其内封装了此事件的所有信息。
低版本IE:window.event
W3C :事件绑定时直接传参数 如:obj.onclick = function(event){};当事件触发时,浏览器会将事件信息封装到事件对象中,然后作为参数传递obj.onclick(event)并且执行之。
事件模型:指嵌套的多个元素都有绑定了同一种事件,当此事件发生时,事件发生的先后顺序是从最外层向最里层,还是从最里层到最外层。
从最里层到最外层 : 冒泡模型(默认)
从最外层向最里层 : 捕捉模型(不建议了)
案例:
<--div id="div1" width="1000px">
<--div id="div2" width="700px">
<--div id="div3" width="300px">
<--font color="green">green<--/font>
<--/div>
<--font color="yellow">yellow<--/font>
<--/div>
<--font color="red">red<--/font>
<--/div>
<--script>
document.getElementById("div3").onclick = function(event){
alert("green");
}
document.getElementById("div2").onclick = function(event){
alert("yellow");
}
document.getElementById("div1").onclick = function(event){
alert("red");
}
<--script>
不过我很少遇到需要事件冒泡的需求,所以我们经常会把冒泡禁止掉:
基于W3C浏览器中:
event.stopPropagation();
基于旧版本的IE中:
e.cancelBubble=true;
<--script>
document.getElementById("div3").onclick = function(event){
alert("green");
stopEventBubble(event);
}
document.getElementById("div2").onclick = function(event){
alert("yellow");
stopEventBubble(event);
}
document.getElementById("div1").onclick = function(event){
alert("red");
stopEventBubble(event);
}
//阻止事件冒泡
functionstopEventBubble(event){
vare=event || window.event;
if(e && e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble=true; }
}
<--/script>
tips:
html部分元素的默认行为及如何控制:
链接:点击后跳转
提交按钮:点击后提交