<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> html { height: auto; overflow: scroll; } body { display: flex; flex-direction: row; justify-content: space-between; padding-top: 4rem; } div { width: 48%; overflow: hidden; } </style> <script src="./plugins/lodash4.17.21/lodash.min.js"></script> <script> // 一些频繁触发的事件,我们不想让它频繁执行,比如 keyup scroll resize mousemove // 防抖:动作执行停止后间隔一定的时间执行,应用场景: 搜索框联想 // 节流:不管执行的频率有多高,需要间隔一定的时间执行一次,应用场景:向下滚动加载数据 // 防抖和节流的区别:防抖:不管动作多少次,只有最后一次执行;节流:一段时间内执行多次,但人为地降低了执行的频率 let i_left = 0; let i_right = 0; document.addEventListener("DOMContentLoaded", () => { document.getElementById("input-text-left").addEventListener("keyup", () => { i_left++; console.log("left第" + i_left + "次"); }); document.getElementById("input-text-right").addEventListener( "keyup", _.debounce(function () { i_right++; console.log("right第" + i_right + "次"); }, 800) ); leftBoxEl = document.getElementById("left-box"); rightBoxEl = document.getElementById("right-box"); document.addEventListener("scroll", () => { imgEl = document.createElement("img"); imgEl.src = "./images/1.jpg"; leftBoxEl.appendChild(imgEl); console.log("left共" + leftBoxEl.querySelectorAll("img").length); }); document.addEventListener( "scroll", _.throttle(() => { imgEl = document.createElement("img"); imgEl.src = "./images/1.jpg"; document.getElementById("right-box").appendChild(imgEl); console.log("right共" + rightBoxEl.querySelectorAll("img").length); }, 1000) ); }); </script> </head> <body> <div id="left-box"> <input type="text" id="input-text-left" /> <img src="./images/1.jpg" /> </div> <div id="right-box"> <input type="text" id="input-text-right" /> <img src="./images/1.jpg" /> </div> </body> </html>
标签:防抖,right,lodash,getElementById,imgEl,document,节流,left From: https://www.cnblogs.com/caroline2016/p/16962502.html