2

利用Css实现按钮节流

 1 year ago
source link: https://www.fly63.com/article/detial/12335
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

节流是指避免过于频繁地执行某个功能,例如保存按钮。 为了避免重复提交或者服务器的考虑,往往需要限制点击行为,否则接口会被频繁请求。 之前基本都是通过js控制节流问题,其实css也可以实现节流。

一、利用pointer-events实现节流

  1. 使用pointer-events来限制点击事件,即禁用点击事件。
  2. 使用动画改变当前按钮是否可以点击
  3. 使用伪类:active触发按钮计时,即点击行为

代码

<button class="throttle" onclick="console.log('节流')">保存</button>
<style>
.throttle {
animation: throttle 2s step-end forwards;
}
.throttle:active {
animation: none;
}
@keyframes throttle {
from {
pointer-events: none;
}
to {
pointer-events: all;
}
}
</style>

如果需要改限制时间,直接改动画时间就行了。

二、监听css的transition实现节流

通过:active去触发transition变化,然后通过监听transition回调去动态设置按钮的禁用状态。

<button onclick="console.log('节流')">保存</button>
<style>
button{
opacity: .99;
transition: opacity 2s;
}
button:not(:disabled):active{
opacity: 1;
transition: 0s;
}
</style>

然后监听transition的起始回调:

// 过渡开始
document.addEventListener('transitionstart', function(ev){
ev.target.disabled = true
})
// 过渡结束
document.addEventListener('transitionend', function(ev){
ev.target.disabled = false
})

上面通过 CSS的思想实现了一个类似于“节流”的功能。 与JS实现相比,实现更精简,更易上手,无框架限制。 

下面总结一下实现的要点:

  • Function throttling 是一种很常见的优化方法,可以有效避免函数执行过于频繁。
  • CSS的实现思路和JS是不一样的。 关键是找到与场景关联的属性。
  • 对一个动画的精确控制,假设有一个动画控制按钮从disabled->clickable变化,使得每次点击动画都重新执行,在执行过程中一直处于disabled状态,从而实现“节流”效果。
  • 也可以通过transition的回调函数动态设置按钮的disabled状态,这样实现的好处是disabled逻辑和业务逻辑完全解耦。

但是, 这个实现还是比较局限的,只限于点击行为,安全性不高,可以通过 ui层面去绕开,像很多时候,可能会在滚动事件或者键盘事件上使用节流,这些场景可以用传统的方式实现。

链接: https://www.fly63.com/article/detial/12335


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK