javascript中级--事件冒泡即取消冒泡

一、事件冒泡

<!DOCTYPE html>
<html lang="en" onclick="alert( 'html')">

<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>
</head>

<body onclick="alert('body')">
    <div style="width:400px;height:400px;background:red" onclick="alert('red')">
        <div style="width:200px;height:200px;background:blue" onclick="alert('blue')">
            <div style="width:100px;height:100px;background:#ccc;" onclick="alert('gray')"></div>
        </div>
    </div>
</body>

</html>

 二、取消冒泡

<!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>Document</title>
    <style>
        #menu {
            width: 100px;
            height: 300px;
            background: #ccc;
            margin-top: 10px;
            display: none;
        }
    </style>
    <script>
        window.onload = function() {
            var oBtn = document.getElementById('btn1');
            var oMenu = document.getElementById('menu');
            oBtn.onclick = function(ev) {
                var oEvent = ev || event;
                oMenu.style.display = "block";
                // alert('a');
                oEvent.cancelBubble = "true"; //阻止冒泡
            }
            document.onclick = function() {
                oMenu.style.display = "none";
            }
        }
    </script>
</head>

<body>
    <input id="btn1" type="button" name="" value="弹出">
    <div id="menu"></div>
</body>

</html>

 

posted @ 2017-03-03 17:43  Mr_W_Blog  阅读(200)  评论(0编辑  收藏  举报