前言
因为要做一个播放器的播放图片旋转动画,像这样子
当音乐播放就转动,停止就暂停。
开始
于是很自然地想到了使用Css3的 animation 动画属性
CSS3 animation(动画) 属性
animation-name
指定要绑定到选择器的关键帧的名称animation-duration
动画指定需要多少秒或毫秒完成animation-timing-function
设置动画将如何完成一个周期animation-delay
设置动画在启动前的延迟间隔。animation-iteration-count
定义动画的播放次数。animation-direction
指定是否应该轮流反向播放动画。animation-fill-mode
规定当动画不播放时(当动画完成时,或当动画有一个延迟未开始播放时),要应用到元素的样式。animation-play-state
指定动画是否正在运行或已暂停。
刚开始我是这样写的
<img
v-if="playerInfo.singerPic"
:src="playerInfo.singerPic"
:class="[
'play_photo',
{ rotate_animation: isPlayBarShow },
{ animation_paused: !isPlaying },
{ animation_play: isPlaying }
]"/>
@keyframes rotate_img {
0% {
transform: translate(-50%, -50%) scale(0.9) rotate(0deg);
}
100% {
transform: translate(-50%, -50%) scale(0.9) rotate(360deg);
}
}
.rotate_animation {
animation: rotate_img 10s linear infinite;
}
.animation_paused {
animation-play-state: paused;
}
.animation_play {
animation-play-state: running;
}
.play_photo {
position: absolute;
top: 50%;
left: 50%;
z-index: -1;
}
问题
在 chrome 里调试没有任何问题,但是真机测试时,出现bug:
- IOS 浏览器中音乐点击暂停,动画直接消失,图片跟没有添加 animation 一样, 直接现出原形,再点播放,动画从刚刚停止的位置继续。这样的体验很不好。
- android 正常。
分析解决
刚开始我怀疑 IOS 系统是不是不支持 animation-play-state: paused
这个属性,但是查阅了一番资料之后,又重新修改了一下代码,主要是 Css,如下:
@keyframes rotate_img {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.rotate_animation {
animation: rotate_img 10s linear infinite normal both;
}
.animation_paused {
animation-play-state: paused;
}
.animation_play {
animation-play-state: running;
}
.play_photo {
width: 0.7rem;
height: 0.7rem;
border-radius: 50%;
position: absolute;
top: calc(50% - 0.35rem);
left: calc(50% - 0.35rem);
z-index: -1;
}
结论
在使用 animation 的 @keyframes
里声明动画的 transform
属性时,尽量减少不变动的属性,否则会出现意想不到的bug。