在做音乐播放器CD唱片背景图旋转时遇到一个坑,就是animation-play-state属性在IOS浏览器下(safari、微信内置浏览器、IOS版chrome),当其对应的动画中有transform: rotate属性时,animation-play-state属性是无效的。下面两个简单例子大家可以在IOS浏览器中简单验证下:
当 @keyframes有transform: rotate属性时,点击pause按钮,动画不会暂停:
http://output.jsbin.com/yuwobiv/1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: red;
position: fixed;
top: 200px;
animation: mymove 5s infinite;
}
@keyframes mymove {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg)
}
}
</style>
</head>
<body>
<div id='3'></div>
<button id='1'>running</button>
<button id='2'>pause</button>
<script type="text/javascript">
document.getElementById('1').addEventListener('click', function() {
document.getElementById('3').style.animationPlayState = 'running'
})
document.getElementById('2').addEventListener('click', function() {
document.getElementById('3').style.animationPlayState = 'paused' ;
console.log('ddddd',document.getElementById('3').style)
})
</script>
</body>
</html>
当无transform: rotate属性且只是简单的top、left等位移时,点击pause按钮,动画会暂停:http://jsbin.com/towaqat/1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: red;
position: fixed;
top: 200px;
animation: mymove 5s infinite;
}
@keyframes mymove {
from {
left: 0px;
}
to {
left: 330px;
}
}
</style>
</head>
<body>
<div id='3'></div>
<button id='1'>running</button>
<button id='2'>pause</button>
<script type="text/javascript">
document.getElementById('1').addEventListener('click', function() {
document.getElementById('3').style.animationPlayState = 'running'
})
document.getElementById('2').addEventListener('click', function() {
document.getElementById('3').style.animationPlayState = 'paused' ;
console.log('ddddd',document.getElementById('3').style)
})
</script>
</body>
</html>
因此为了兼容性,我在做CD背景图旋转时,是按照歌曲时间进度换算成对应的角度(比如我的背景图旋转一个周期是20s,那么我可以写个函数将歌曲时间进度转换成CD背景图对应的角度。),当暂停时(暂停时,取消动画,播放时重新生成动画),获取当前歌曲的时间进度,然后通过前述的函数换算出对应的角度,然后只需将包裹CD背景图的父容器旋转下相应角度即可。这样,点击开始播放时,CD会在原来的角度基础上继续旋转从而达到了暂停的效果。具体可见:https://github.com/have-not-BUG/vue-music/commit/f10e33e623ef27457fcf4c0ee88d2d1a60d7ce7c
*本文版权归本人即简书笔名:该账户已被查封 所有,如需转载请注明出处。谢谢!
网友评论