哪家企业网站建设好,建设一个跟京东一样的网站,vip电影网站建设,制作企业网站页面多少钱函数节流是一个我们在项目开发中常用的优化手段#xff0c;可以有效避免函数过于频繁的执行。一般函数节流用在scroll页面滚动#xff0c;鼠标移动等。
为什么需要节流呢#xff0c;因为触发一次事件就会执行一次事件#xff0c;这样就形成了大量操作dom,会出现卡顿的情况…函数节流是一个我们在项目开发中常用的优化手段可以有效避免函数过于频繁的执行。一般函数节流用在scroll页面滚动鼠标移动等。
为什么需要节流呢因为触发一次事件就会执行一次事件这样就形成了大量操作dom,会出现卡顿的情况。
一、传统JS节流实现方式 /* 1.时间戳实现 */function throttle(func, delay) {let prev 0return function(...args){let now new Date()if(now - prev delay){prev new Date()func.apply(this, args)}}}/* 定时器实现 */function throttle(func, delay) {let timer nullreturn function(...args) {if(!timer){timer setTimeout(() {timer nullfunc.apply(this, args)},delay)}}}二、CSS实现 1.实现思路
我们可以使用css的pointer-events禁用点击事件对事件进行控制。 使用animation设置禁用时间对时间进行限制。 使用:active点击行为作为触发时机
可以这样理解一个CSS动画从禁用到可点击的变化每次点击时让这个动画重新执行一遍在整个执行过程设置的时间范围内一直处于禁用的状态这是不是就有点像节流的功能。
2.具体实现 假设一个按钮连续点击按钮就会一直触发事件。
button onclickconsole.log(111)点击按钮/button使用pointer-events实现一个动画从禁用到可点击。 keyframes throttle {from {color: green;pointer-events: none;}to {color: black;pointer-events: all;}}button {animation: throttle 3s step-end forwards;}button:active {animation: none;}