# Animation
- 作用:创建一个Animation对象实例
- 调用:new Animation(effect, timeline)
- 入参:KeyframeEffect对象, documentTimeLine (opens new window)
- 返回:Animation
<body>
<style>
.ball {
background-color: rgb(173, 255, 154);
height: 100px;
width: 100px;
border-radius: 50px;
}
</style>
<div class="ball"></div>
<script>
const ball = document.querySelector('.ball');
const keyFrames = new KeyframeEffect(
ball,
[{
transform: 'translateY(0%)'
},
{
transform: 'translateY(100%)'
},
], {
duration: 1000,
fill: 'backwards'
}
);
const animation = new Animation(keyFrames, document.timeline);
ball.addEventListener('click', () => animation.play());
</script>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<body>
<style>
body {
padding: 0;
margin: 0;
}
.wrapper {
position: relative;
width: 100vw;
height: 100vh;
overflow-x: hidden;
}
.menu {
position: absolute;
width: 100vw;
height: 100vh;
right: -100vw;
background-color: rgb(173, 255, 154);
}
</style>
<div class="wrapper">
<div class="menu"></div>
<button>控制按钮</button>
</div>
<script>
const menu = document.querySelector('.menu');
const button = document.querySelector('button');
const inFrame = new KeyframeEffect(
menu,
[{
right: "-100%",
},
{
right: "-20%",
},
], {
duration: 200,
fill: 'forwards'
}
);
const outFrame = new KeyframeEffect(
menu,
[{
right: "-20%",
},
{
right: "-100%",
},
], {
duration: 200,
fill: 'forwards'
}
);
const toggle = (() => {
let state = 'out';
return () => {
if (state === 'out') {
const inAni = new Animation(inFrame, document.timeline);
inAni.play();
state = 'in';
} else {
const outAni = new Animation(outFrame, document.timeline);
outAni.play();
console.log(outAni.playbackRate);
state = 'out';
}
}
})();
button.addEventListener('click', () => toggle());
</script>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74