zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

节流还在用JS吗?CSS也可以实现哦

2023-04-18 16:41:20 时间

函数节流是一个我们在项目开发中常用的优化手段,可以有效避免函数过于频繁的执行。一般函数节流用在scroll页面滚动,鼠标移动等。

为什么需要节流呢,因为触发一次事件就会执行一次事件,这样就形成了大量操作dom,会出现卡顿的情况。

一、传统JS节流实现方式

   /* 1.时间戳实现 */
    function throttle(func, delay) {
      let prev = 0
      return function(...args){
        let now = new Date()
        if(now - prev > delay){
          prev = new Date()
          func.apply(this, args)
        }
      }
    }

    /* 定时器实现 */
    function throttle(func, delay) {
      let timer = null
      return function(...args) {
        if(!timer){
          timer = setTimeout(() => {
            timer = null
            func.apply(this, args)
          },delay)
        }
      }
    }

二、CSS实现
1.实现思路

我们可以使用css的pointer-events禁用点击事件对事件进行控制。
使用animation设置禁用时间,对时间进行限制。
使用:active点击行为作为触发时机

可以这样理解,一个CSS动画从禁用可点击的变化,每次点击时让这个动画重新执行一遍,在整个执行过程设置的时间范围内一直处于禁用的状态,这是不是就有点像节流的功能。

2.具体实现
假设一个按钮,连续点击按钮就会一直触发事件。

<button onclick="console.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;
  }

在这里插入图片描述