css throttle节流方法
节流的定义
在触发任务的第一时间执行任务,并且设定定时器,在定时器设定的时间还未结束时触发任务,也不会去执。规定一个时间n,n秒内,将触发的事件合并为一次并执行。
js常见的处理方式:
const throttle = function(func, delay) {
let timer = null
return function() {
const context = this
const args = arguments
if(!timer) {
timer = setTimeout(() =>{
func.apply(context, args)
timer = null
}, delay)
}
}
通过css 处理节流问题
vue页面创建一个按钮,并设置点击事件
<template>
<el-button id="save-button" type="primary" @click="clickSave">save</el-button>
<template>
export default{
methods:{
clickSave(){
console.log('click save')
}
}
}
连续点击按钮时,事件一直被调用,导致性能受到影响。
css控制鼠标点击事件是通过 pointer-event 属性
pointer-event: none; //禁止点击
通过动画控制可点击切换
@keyframes throttle {
from {
pointer-event: none;
}
to {
pointer-event: all;
}
}
#save-button {
animation: throttle 3s step-end forwards; // forwards 一直保持all状态
}
// 触发动画的时机 点击的状态设置为none
#save-button:active{
pointer-event: none;
}