12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- .box1{
- width: 400px;
- height: 400px;
- background-color: red;
- }
- .box2{
- width: 200px;
- height: 200px;
- background-color: blue;
- }
- </style>
- </head>
- <body>
- <div class="box1">
- <div class="box2"></div>
- </div>
- <script>
- var oBox1 = document.getElementsByClassName("box1")[0];
- var oBox2 = document.getElementsByClassName("box2")[0];
- // 事件冒泡
- // 事件冒泡:事件从最当前触发事件的元素开始,然后逐步向上冒泡到祖先元素,直到到达文档的根元素(html标签)。
- // 事件冒泡的过程中,事件处理函数会按照元素的层级关系,从内到外依次执行。
- // oBox1.onclick = function(){
- // console.log("box1")
- // }
- // oBox2.onclick = function(){
- // console.log("box2")
- // }
- oBox1.addEventListener("click",function(){
- console.log("4-box1")
- },false)
- oBox2.addEventListener("click",function(e){
- console.log("3-box2")
- // 阻止事件冒泡
- e.stopPropagation();
- },false)
- // 事件捕获
- // 事件捕获:事件从文档的根元素(html标签)开始,然后逐步向下捕获到触发事件的元素,直到到达目标元素。
- // 事件捕获的过程中,事件处理函数会按照元素的层级关系,从外到内依次执行。
- // oBox1.addEventListener("click",function(){
- // console.log("1-box1")
- // },true)
- // oBox2.addEventListener("click",function(){
- // console.log("2-box2")
- // },true)
- </script>
- </body>
- </html>
|