zheng 1 semana atrás
pai
commit
3d3684897c
1 arquivos alterados com 50 adições e 0 exclusões
  1. 50 0
      11.复习/5.防抖.html

+ 50 - 0
11.复习/5.防抖.html

@@ -0,0 +1,50 @@
+<!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;
+            text-align: center;
+            line-height: 300px;
+            color: #ff0;
+            font-size: 30px;
+            background-color: #f00;
+        }
+    </style>
+</head>
+
+<body>
+    <div id="box"></div>
+    <script>
+        /**
+         * 防抖:
+         * 点击事件 在事件触发后 等待一段时间在执行回调函数
+         * 在等待的时间内 若再次点击事件 则重新触发事件 重新计时
+         * 搜索框输入 滚动事件 resize窗口大小
+         */
+        const box = document.getElementById("box");
+        let x = 0;
+
+        function CountMain() {
+            box.innerHTML = ++x;
+        }
+
+        function debounce(fn, delay) {
+            let timer = null;
+            return function () {
+                if (timer) clearTimeout(timer);
+                timer = setTimeout(function () {
+                    fn();
+                }, delay)
+            }
+        }
+        box.addEventListener("click", debounce(CountMain, 3000))
+    </script>
+</body>
+
+</html>