您现在的位置是:首页 > 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;
}
相关文章
- 2_注释与变量_javascript_脑图系列
- Undertow容器在Springboot中如何自定义修改文件名
- vue中使用wangEditor出现光标乱跳的问题【前端】
- 春节到了分享一哈,用代码画一束玫瑰花
- SpringBoot系列之集成MybatisPlus操作指南
- nodejs的优缺点
- NodeJS 入门了解
- nodejs 安装步骤
- 在centos7安装nodejs并升级nodejs到最新版本
- 用nodejs搭建一个简单的web服务器
- nodeJS操纵数据库
- nodejs-websocket代码nodejs版本
- Nodejs中的url模块
- nodejs中的fs模块
- nodejs事件循环
- cordova与nodejs
- nodejs创建一个简单的服务器
- nodejs实现多进程
- 用 JavaScript 构建命令行应用
- autojs-ocr-easyedge-nodejs