|
@@ -0,0 +1,90 @@
|
|
|
+<!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;
|
|
|
+ }
|
|
|
+ .box3{
|
|
|
+ width: 100px;
|
|
|
+ height: 100px;
|
|
|
+ background-color: green;
|
|
|
+ }
|
|
|
+ </style>
|
|
|
+</head>
|
|
|
+<body>
|
|
|
+ <div class="box1">
|
|
|
+ <div class="box2">
|
|
|
+ <div class="box3"></div>
|
|
|
+ </div>
|
|
|
+ </div>
|
|
|
+ <script>
|
|
|
+ // 事件冒泡 当有多个元素嵌套的时候 并且绑定相同事件当内层元素触发事件的时候 会逐层触发外层元素的事件
|
|
|
+ var oBox1 = document.getElementsByClassName("box1")[0];
|
|
|
+ var oBox2 = document.getElementsByClassName("box2")[0];
|
|
|
+ var oBox3 = document.getElementsByClassName("box3")[0];
|
|
|
+ // oBox1.onclick = function(){
|
|
|
+ // console.log("box1");
|
|
|
+ // }
|
|
|
+
|
|
|
+ // oBox2.onclick = function(){
|
|
|
+ // console.log("box2");
|
|
|
+ // }
|
|
|
+ // oBox3.onclick = function(e){
|
|
|
+ // console.log("box3");
|
|
|
+ // // 阻止事件冒泡
|
|
|
+ // // e.stopPropagation();
|
|
|
+ // }
|
|
|
+
|
|
|
+ // 实用on赋值方式绑定事件与addEventListener绑定事件区别
|
|
|
+ // addEventListener 可以重复绑定相同事件 而 on方式不可以
|
|
|
+ // on方式可以重复绑定相同事件 但是只执行最后一次绑定事件
|
|
|
+ // addEventListener 可以触发事件捕获 而 on方式不可以
|
|
|
+ // addEventListener 可以使用 removeEventListener 移除事件
|
|
|
+ // on绑定事件 则需要给事件负一个空值
|
|
|
+ //事件冒泡 addEventListener 第三个参数为false 事件冒泡
|
|
|
+ // oBox1.addEventListener("click",function(){
|
|
|
+ // console.log("box1");
|
|
|
+ // },false)
|
|
|
+ // oBox2.addEventListener("click",function(){
|
|
|
+ // console.log("box2");
|
|
|
+ // },false)
|
|
|
+ // oBox3.addEventListener("click",function(e){
|
|
|
+ // console.log("box3");
|
|
|
+ // },false)
|
|
|
+
|
|
|
+ // 事件捕获 addEventListener 第三个参数为true 事件捕获
|
|
|
+ // oBox1.addEventListener("click",function(){
|
|
|
+ // console.log("box1");
|
|
|
+ // },true);
|
|
|
+ // oBox2.addEventListener("click",function(){
|
|
|
+ // console.log("box2");
|
|
|
+ // },true)
|
|
|
+ // oBox3.addEventListener("click",function(e){
|
|
|
+ // console.log("box3");
|
|
|
+ // },true)
|
|
|
+
|
|
|
+ // addEventListener 三个参数 第一个事件名称 第二个事件处理函数 第三个事件是否捕获还是冒泡
|
|
|
+
|
|
|
+ function foo(){
|
|
|
+ console.log("hello");
|
|
|
+ }
|
|
|
+ // 回调函数 当一个方法执行完毕之后或者触发事件的时候 回来再执行的函数
|
|
|
+ // 如果函数是用作于回调函数使用那么后边括号必须省略
|
|
|
+ oBox1.addEventListener("click",foo);
|
|
|
+
|
|
|
+ oBox1.removeEventListener("click",foo);
|
|
|
+
|
|
|
+ </script>
|
|
|
+</body>
|
|
|
+</html>
|