|
@@ -0,0 +1,56 @@
|
|
|
|
|
+<!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>
|
|
|
|
|
+ .box{
|
|
|
|
|
+ width: 100px;
|
|
|
|
|
+ height: 50px;
|
|
|
|
|
+ background-color: red;
|
|
|
|
|
+ text-align: center;
|
|
|
|
|
+ line-height: 50px;
|
|
|
|
|
+ }
|
|
|
|
|
+ </style>
|
|
|
|
|
+</head>
|
|
|
|
|
+<body>
|
|
|
|
|
+ <div class="box">按钮</div>
|
|
|
|
|
+ <script>
|
|
|
|
|
+ var oBox = document.getElementsByClassName("box")[0];
|
|
|
|
|
+ // console.log(oBox[0]);
|
|
|
|
|
+ // 通过on 绑定事件 on + 事件名称 = 事件处理函数
|
|
|
|
|
+ // click 点击事件 当用户点击某一个元素的时候触发
|
|
|
|
|
+ // on 绑定事件仅能绑定一个事件 如果多次绑定 则后面的会覆盖前面的
|
|
|
|
|
+ // oBox.onclick = function(){
|
|
|
|
|
+ // console.log("点击了按钮");
|
|
|
|
|
+ // }
|
|
|
|
|
+ // oBox.onclick = function(){
|
|
|
|
|
+ // console.log("又点击了按钮");
|
|
|
|
|
+ // }
|
|
|
|
|
+ // oBox.onclick = null; // 取消点击事件
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ // 通过addEventListener 来绑定事件
|
|
|
|
|
+ // addEventListener 后面可以接两个参数 第一个参数是事件名称 第二个参数是事件处理函数
|
|
|
|
|
+ // 事件名称不需要加on
|
|
|
|
|
+ // addEventListener 可以对同一个标签绑定多次事件
|
|
|
|
|
+ // oBox.addEventListener("click",function(){
|
|
|
|
|
+ // console.log("通过addEventListener绑定点击事件");
|
|
|
|
|
+ // });
|
|
|
|
|
+ // oBox.addEventListener("click",function(){
|
|
|
|
|
+ // console.log("又通过addEventListener绑定点击事件");
|
|
|
|
|
+ // });
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+ // 取消通过addEventListener绑定的事件 使用removeEventListener 需要传入和绑定时一样的函数才可以取消成功
|
|
|
|
|
+ var foo = function(){
|
|
|
|
|
+ console.log("通过addEventListener绑定点击事件");
|
|
|
|
|
+ };
|
|
|
|
|
+ oBox.addEventListener("click",foo);
|
|
|
|
|
+ oBox.removeEventListener("click",foo);
|
|
|
|
|
+ </script>
|
|
|
|
|
+</body>
|
|
|
|
|
+</html>
|