阻止冒泡,阻止默认行为

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Meikooo1/article/details/80656500
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .box{
                
                width:400px;
                height: 400px;
                background: red;
            }
            .box1{
                
                width:200px;
                height:200px;
                background: blue;
            }
            .box2{
                
                width:100px;
                height:100px;
                background: orange;
            }
        </style>
        <script>
            
            //事件的target属性 : 存放触发事件的节点对象
            onload = function() {
                
                
                //事件的冒泡 (浏览器默认的)
                    //事件传递机制: 在页面上是从上层往下层传递事件
                
                //事件的捕获
                    //事件传递机制: 在页面上是从下层往上层传递事件
                
                function $(id){
                    return document.getElementById(id);
                }
                var box=$('box');
                var box1=$('box1');
                var box2=$('box2');             
                
                box.onclick=function(){
                    
                    alert('box');
                }               
                box1.onclick=function(){
                    
                    alert('box1');
                }
                
                box2.onclick=function(e){
                    
                    alert('box2');
                    
                    var event=e || window.event;
                    //阻止事件的冒泡 兼容性写法                
                    if(event.stopPropagation){
                        event.stopPropagation()
                    }else{
                        event.cancelBubble=true;
                    }       
                }
                
                
            }
        </script>
    </head>
    <body>
        <div class="box" id="box">
            box         
            <div id="box1" class="box1">
                
                box1
                <div id="box2" class="box2">
                    
                    box2
                </div>
            
            </div>
        </div>
        
        
        
    </body>
</html>


展开阅读全文

没有更多推荐了,返回首页