6

CSS实现防止按钮重复点击,双击进入两次单机的情况

 1 year ago
source link: https://www.haorooms.com/post/css_throttle_btn
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

CSS实现防止按钮重复点击,双击进入两次单机的情况

2022年11月17日 23次浏览

之前有文章写过如何避免双击进入两次单机的情况,当然你也可以通过节流来实现,实现的方案很多,今天主要介绍一下如何通过css来实现,也就是css来实现按钮节流。

我们可以用pointer-events 或者disabled等方式,对按钮进行节流,如何操作呢?

pointer-events加css的动画来控制,也就是动画时长时间内只能点击一次,代码如下:

button{
  animation: throttle 2s step-end forwards;
}
button:active{
  animation: none;
}
@keyframes throttle {
  from {
    pointer-events: none;
  }
  to {
    pointer-events: all;
  }
}

解释:这里动画的缓动函数设置成了阶梯曲线,step-end,它可以很方便的控制pointer-events的变化时间点。pointer-events在0~2秒内的值都是none,一旦到达2秒,就立刻变成了all,由于是forwards,会一直保持all的状态。

其实,根据这个,我们有很多按钮动画特性可以实现,特别是利用active

:root{
  --primary-color: royalblue;
}
.button{
  padding: 5px 16px;
  color: #000000d9;
  border: 1px solid #d9d9d9;
  background-color: transparent;
  border-radius: 2px;
  line-height: 1.4;
  box-shadow: 0 2px #00000004;
  cursor: pointer;
  transition: .3s;
}
.button:hover{
  color: var(--primary-color);
  border-color: currentColor;
}

.button::after{
  content: '';
  position: absolute;
  inset: 0;
  border-radius: inherit;
  opacity: 0.4;
  transition: .3s;
}

假如我们通过如下方式触发动画的话

.button:active::after{
  box-shadow: 0 0 0 6px var(--primary-color);
  opacity: 0;
}

发现动画出现了,可能抬起之后瞬间结束,比较生硬。 那时因为:active。:active只有在鼠标按下时才会起作用,通常在点击一个按钮时,都是轻轻地点击,而不是长按,如果在:active上添加动画,那么在鼠标抬起的时候,动画一般都没有结束,所以会导致在鼠标抬起的时候,动画马上就停止了,如果是transition,还会有一个“回退”的过渡效果。

所以改进如下:

.button::after{
  /*其他样式*/
  opacity: 0;
  box-shadow: 0 0 0 6px var(--primary-color);
  transition: .3s;
}
/*点击*/
.button:active::after{
  box-shadow: none;
  opacity: 0.4;
  transition: 0s; /*取消过渡*/
}

这样就比较完美,我们可以再active的时候取消动画。和上面节流的原理一样。

本文,除了css控制点击节流之外,css按钮动画,添加动画的时候,我们给按钮添加一个动画,

.button{
  animation: 动画名字 1s;
}

我们可以通过active控制结束动画,例如:

.button:active{
  animation: none;
}

这样就可以实现比较好看的点击动画效果。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK