fengchuanyu 8 godzin temu
rodzic
commit
2d1b1ac050
1 zmienionych plików z 69 dodań i 0 usunięć
  1. 69 0
      4_BOM&DOM/练习题2_按钮倒计时.html

+ 69 - 0
4_BOM&DOM/练习题2_按钮倒计时.html

@@ -0,0 +1,69 @@
+<!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: 300px;
+            height: 300px;
+            background-color: #aaa;
+            position: fixed;
+            top: 50%;
+            left: 50%;
+            margin-top: -150px;
+            margin-left: -150px;
+            text-align:center;
+        }
+        p{
+            font-size: 50px;
+            color: #fff;
+            font-weight: bold;
+            text-align: center;
+        }
+        button{
+            width: 100px;
+            height: 50px;
+            background-color:#fff;
+            font-size:30px;
+        }
+    </style>
+</head>
+<body>
+    <div class="box">
+        <p>100</p>
+        <button>开始</button>
+    </div>
+    <script>
+        // 第一步:获取要控制的元素
+        var num = document.getElementsByTagName("p")[0];
+        var btn = document.getElementsByTagName("button")[0];
+        var timer = 0;
+        // 第二步:给按钮绑定事件
+        btn.onclick = function(){
+            if(btn.innerText == "开始"){
+                btn.innerText = "暂停";
+                // 开始倒计时-1
+                timer = setInterval(function(){
+                    num.innerText--;
+                },1000)
+                console.log(timer);
+            }else{
+                btn.innerText = "开始"
+                // 停止定时器
+                console.log(timer)
+                clearInterval(timer)
+            }
+        }
+
+
+        // 如果使用on绑定事件绑定多次那么后边绑定的会覆盖前面绑定的事件
+        // var a = 1;
+        // var a = 2;
+        // btn.onclick = function(){
+        //     console.log("hello")
+        // }
+    </script>
+</body>
+</html>