css 实现铃铛抖动效果
最近在写站内信的系统功能时,希望在前端按钮上做一个抖动效果,当websocket消息通知的时候,铃铛按钮就会响应作出晃动的动作。
HTML部分
使用的vue,省略部分代码
<!--两种方式-->
<!--一、使用i标签实现的bell-->
<i id="bell" class="vue-icon-bell-o"></i>
<!--二、使用div标签实现的bell,css设置背景图片-->
<div id="bell"></div>
JS部分
希望的效果是,当websocket的onopen和onmessage的时候都能响应这个特效。
···
doShake(){
this.startShake();
// 延迟两秒后停止晃动
setTimeout(()=>{
this.stopShake();
},2000);
},
startShake() {
var bell = document.getElementById('bell');
bell.classList.add('shake-animation');
},
stopShake() {
var bell = document.getElementById('bell');
bell.classList.remove('shake-animation');
// 为了让晃动停止的动作看起来没有那么突兀
setTimeout(()=>{
bell.style.transform = 'rotateZ(0deg)';
},2000);
},
···
css部分
#bell{
display:block;
width:30px;
height:30px;
// div的方式引入,修改背景图
background: url(../assets/svg/bell.svg) no-repeat;
background-size: cover;
}
.shake-animation {
animation: shake 0.8s infinite;
animation-fill-mode: forwards;
}
// 关键帧
@keyframes shake {
0% {
transform: rotateZ(0deg);
transition-timing-function: cubic-bezier(0.215,.61,.355,1);
}
10% {
transform: rotateZ(-12deg);
transition-timing-function: cubic-bezier(0.215,.61,.355,1);
}
20% {
transform: rotateZ(12deg);
transition-timing-function: cubic-bezier(0.215,.61,.355,1);
}
28% {
transform: rotateZ(-10deg);
transition-timing-function: cubic-bezier(0.215,.61,.355,1);
}
36% {
transform: rotateZ(10deg);
transition-timing-function: cubic-bezier(0.755,.5,.855,.06);
}
42% {
transform: rotateZ(-8deg);
transition-timing-function: cubic-bezier(0.755,.5,.855,.06);
}
48% {
transform: rotateZ(8deg);
transition-timing-function: cubic-bezier(0.755,.5,.855,.06);
}
52% {
transform: rotateZ(-4deg);
transition-timing-function: cubic-bezier(0.755,.5,.855,.06);
}
56% {
transform: rotateZ(4deg);
transition-timing-function: cubic-bezier(0.755,.5,.855,.06);
}
60% {
transform: rotateZ(0deg);
transition-timing-function: cubic-bezier(0.755,.5,.855,.06);
}
100% {
transform: rotateZ(0deg);
transition-timing-function: cubic-bezier(0.215,.61,.355,1);
}
}