1、概念

事件冒泡:如果元素A嵌套在元素B中,那么A被点击不仅A的onclick事件会被触发,B的onclick也会被触发。触发的顺序是“由内而外”。


2、取消事件冒泡

谷歌、IE

window.event.cancelBubble = true;

火狐

e.stopPropagation();


示例代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Javascript测试</title>
    <script type="text/javascript">
        onload = function(){
            document.getElementById('dv').onclick=function(){
                alert(this.id);
            };
            document.getElementById('p1').onclick=function(){
                alert(this.id);
                window.event.cancelBubble = true;//取消事件冒泡
            };
        };
    </script>
</head>
<body>
    <div id="dv" style="width:300px;height:180px;border:solid 1px red;">
        <p id="p1" style="width:200px;height:50px;background-color: aquamarine;">这里是P标签</p>
    </div>
</body>
</html>

效果图一(firefox不支持window.event.cancelBubble)

Javascript中的事件冒泡_javascript

效果图二(IE)

Javascript中的事件冒泡_Java_02




示例代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Javascript测试</title>
    <script type="text/javascript">
        onload = function(){
            document.getElementById('dv').onclick=function(){
                //alert(this.id);
                alert(window.event.srcElement.id);//通过srcElement获取到最原始的element的id
            };
            document.getElementById('p1').onclick=function(){
                alert(this.id);
                //window.event.cancelBubble = true;//取消事件冒泡
            };
        };
    </script>
</head>
<body>
    <div id="dv" style="width:300px;height:180px;border:solid 1px red;">
        <p id="p1" style="width:200px;height:50px;background-color: aquamarine;">这里是P标签</p>
    </div>
</body>
</html>

效果图

Javascript中的事件冒泡_Java_03


再次强调this表示的是当前监听的事件

event.srcElement是引发事件的对象(冒泡)