美文网首页
阻止事件冒泡

阻止事件冒泡

作者: 阿布朗迪 | 来源:发表于2018-10-10 20:16 被阅读0次
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>冒泡事件</title>
    <style>
        #box1{
            width: 300px;
            height: 300px;
            background: #f00;
        }
        #box2{
            width: 150px;
            height: 150px;
            background: #ff0;
        }
        #box3{
            width: 100px;
            height: 100px;
            background: #0f0;
        }
    </style>
</head>
<body>
    <div id="box1">
        <div id="box2">
            <div id="box3">
            </div>
        </div>
    </div>
</body>
<script>
    var box1 = document.querySelector( '#box1');
    var box2 = document.querySelector( '#box2');
    var box3 = document.querySelector( '#box3');

    box1.onclick = function(  ){
        alert( 1 )
    }
    box2.onclick = function( eve ){
        var e = eve || window.event;
        stopPro( e );
        alert( 2 )  
    }
    box3.onclick = function( eve ){
        var e = eve || window.event;
        stopPro( e )
        alert( 3 )
    }
    
    function stopPro( e ){
        if( e.stopPropagation){
            e.stopPropagation();
        }else{
            e.cancelBubble =  true;
        }
    }
</script>
</html>

相关文章

网友评论

      本文标题:阻止事件冒泡

      本文链接:https://www.haomeiwen.com/subject/nmpmaftx.html