ITPub博客

首页 > 应用开发 > IT综合 > JavaScript之坑了我--事件模型细节

JavaScript之坑了我--事件模型细节

原创 IT综合 作者:eBusinessMan 时间:2015-11-04 21:07:56 0 删除 编辑


  首先我们还得了解:
  事件对象:事件发生时系统自动产生的对象,其内封装了此事件的所有信息。

低版本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);
}

//阻止事件冒泡  
function stopEventBubble(event){ 
 var e=event || window.event; 
 if (e && e.stopPropagation){
            e.stopPropagation();    
        } else{
            e.cancelBubble=true;
        }

}
<--/script

   
                                                                 



 html部分元素的默认行为及如何控制:

     链接:点击后跳转 

     提交按钮:点击后提交

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29900383/viewspace-1822690/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-09-21

  • 博文量
    46
  • 访问量
    134910