事件的冒泡传播

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        #outer{
            width:300px;
            height:300px;
            margin:100px auto;
            background: red;
        }
        #inner{
            width:200px;
            height:200px;
            margin: auto;
            background: yellowgreen;
        }
        #center{
            width:100px;
            height:100px;
            background: pink;
            margin: auto;
        }
    </style>
</head>
<body>
<div id="outer">
    <div id="inner">
        <div id="center">

        </div>
    </div>
</div>
<script>
    var outer = document.getElementById("outer");
    var inner = document.getElementById("inner");
    var center = document.getElementById("center");
    outer.onclick = function () {
        console.log("outer")
    }
    inner.onclick = function () {
        console.log("inner")
    }
    center.onclick = function (e) {
        e = e || window.event;
        // 阻止事件的默认行为
        e.preventDefault = e.preventDefault || function () {
            e.returnValue = false;
        }
        // 阻止事件的冒泡传播
        e.stopPropagation = e.stopPropagation || function () {
            e.cancelBubble=true;
        }
        e.stopPropagation();
        console.log("center")
    }
    // 事件冒泡传播: 给当前元素的子孙元素的事件行为绑定方法,当触发子孙元素身上的事件时,当前元素对应的事件行为也会随着触发;这种事件从内向外传播执行的方式就是事件冒泡传播;

    // 阻止事件的冒泡传播;  e.stopPropagation();

    // onmouseover   onmouseout
    // onmouseenter  onmouseleave
    // 区别: onmouseenter和onmouseleave不具有事件冒泡传播的机制;
    outer.onmouseenter= function () {
        console.log(100);
    }
    inner.onmouseenter = function () {
        console.log(200);
    }
</script>
</body>
</html>
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值