首页 > 技术文章 > js html 事件冒泡

yaowen 2016-08-01 11:24 原文

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width:100px; height:200px; border: 1px solid red; display: none;}
</style>
点击按钮显示div1,点击按钮其余地方隐藏div1,点击按钮其余地方会因为冒泡触发document的点击事件所以这里只需要写document的点击事件隐藏div1就可以实现点击其余地方都让div1隐藏。
<script>
window.onload = function() {
    /*
事件冒泡:点击子级元素接收到事件后,会把他接收到的事件传播给他的父级,也就是父级也会接收到子级的事件,一直到document,window。
调用var ev=ev||event,ev.cancelBubble=false阻止向父类冒泡,
    阻止冒泡 : 当前要阻止冒泡的事件函数中调用 event.cancelBubble = true;
    */
    var oBtn = document.getElementById('btn');
    var oDiv = document.getElementById('div1');
    oBtn.onclick = function(ev) {
        var ev = ev || event;
        ev.cancelBubble = true;//阻止当前对象的当前事件的冒泡,不出发document的点击事件又让div1隐藏了。
        oDiv.style.display = 'block';
    }
    document.onclick = function() {//点击p也会出发document点击事件因为冒泡,实现点击非按钮任意地方让div1的隐藏。
        /*setTimeout(function() {
            oDiv.style.display = 'none';
        }, 1000);*/
        oDiv.style.display = 'none';
    }
}
</script>
</head>

<body>
    <input type="button" value="按钮" id="btn" />
    <div id="div1"></div>
    <p>ppppp</p>
    <p>ppppp</p>
    <p>ppppp</p>
    <p>ppppp</p>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height: 200px; background: red; position: absolute; left: -100px; top: 100px;}
#div2 {width: 30px; height: 60px; position: absolute; right: -30px; top: 70px; background: black; color: white; text-align: center;}
</style>
<script>
window.onload = function() {
    //只需要对div1加事件,因为div2接收到事件会冒泡传递给div1。
    var oDiv = document.getElementById('div1');
    oDiv.onmouseover = function() {
        this.style.left = '0px';
    }
    oDiv.onmouseout = function() {
        this.style.left = '-100px';
    }
}
</script>
</head>
<body>
    <div id="div1">
        <div id="div2">分享到</div>
    </div>
</body>
</html>

 

推荐阅读