背景
在做一个h5项目的时候,有这样一个需求:
点击确定按钮的时候,如果用户没有勾选协议,就给协议添加一个抖动的动画,用来引起用户的注意,提示用户这里是需要勾选的。但是在实现这个效果的时候发现,点击了确定按钮抖动了一次以后,我们没有勾选协议,直接再去点击确定按钮就会没有了抖动的效果。思来想去发现,添加动画的那个类名在加了第一次之后一直就在了,所以后面再点击就没有抖动效果了。于是乎,想到了setTimeout() 和 clearTimeout()
首先我们先看一下setTimeout()、clearTimeout()的定义和用法:
setTimeout()定义和用法
定义:
setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式。
语法:
setTimeout(code,millisec)
参数 | 描述 |
---|---|
code | 必需。要调用的函数后要执行的 JavaScript 代码串。 |
millisec | 必需。在执行代码前需等待的毫秒数。 |
clearTimeout()定义和用法
定义:
clearTimeout() 方法可取消由 setTimeout() 方法设置的 timeout。
语法:
clearTimeout(id_of_settimeout)
参数 | 描述 |
---|---|
id_of_settimeout | 由 setTimeout() 返回的 ID 值。该值标识要取消的延迟执行代码块。 |
然后我们来看一下项目的解决方法:
以下是代码实现的效果

以下是实现代码
- html代码:
<div class="pact" >
<span :class="[check?'pact__check-on pact__check': 'pact__check']" @click="checkAction()"></span>
<span class="pact__text">你已阅读并同意</span>
<a :class="[make_shake?'pact__text-color shaking_animation':'pact__text-color']" href="#">《测试协议》</a>
</div>
- css代码:
.shaking_animation{
animation-duration: 300ms;
animation-iteration-count: 2;
animation-name: move;
}
@keyframes move {
from {
transform: translateX(0px);
}
25% {
transform: translateX(-16px);
}
50% {
transform: translateX(0px);
}
75% {
transform: translateX(16px);
}
to {
transform: translateX(0px);
}
}
- js代码:
authClick: function(){
var self = this;
if(this.check){
self.make_shake = false;
}
else{
self.make_shake = true
let timeout = setTimeout(()=>{
self.make_shake = false;
clearTimeout(timeout)
},300)
}
}
这里实现的方法是:设置一个定时器,过了300毫秒后,把make_shake重新设置为false,已达到300毫秒之后我们去掉动画shaking_animation类名。然后清空这个定时器。
结束语:
写的不好多多见谅。END!!!!!!