123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- #box1 {
- width: 200px;
- height: 200px;
- background-color: yellowgreen;
- }
- #s1 {
- background-color: yellow;
- }
- </style>
- <script>
- window.onload = function () {
- /**
- * 事件的冒泡(Bubble)
- * -所谓的冒泡指的就是事件向上传导,当后代元素上的事件被触发时,
- * 其祖先元素的相同事件也会被触发
- * -在开发中大部分情况冒泡都是有用的,如果不希望发生事件冒泡,
- * 可以通过事件对象来取消冒泡
- */
- //为s1绑定一个单击响应函数
- var s1 = document.getElementById("s1");
- s1.onclick = function (event) {
- event = event || window.event;
- alert("span的单击响应函数");
- //取消冒泡
- //可以将事件对象的cancelBubble设置为true,即可取消冒泡
- event.cancelBubble = true;
- };
- //为box1绑定一个单击响应函数
- var box1 = document.getElementById("box1");
- box1.onclick = function () {
- alert("div的单击响应函数");
- event.cancelBubble = true;
- };
- //为body绑定一个单击响应函数
- document.body.onclick = function(){
- alert('body的单击响应函数');
- };
- };
- </script>
- </head>
- <body>
- <div id="box1">
- 我是box1
- <span id="s1">我是span</span>
- </div>
- </body>
- </html>
|