示例代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>webAnimationsAPI</title>
<style>
.box {
width: 200px;
height: 200px;
position: fixed;
background: lightblue;
right:0;
}
</style>
</head>
<body>
<div class="box"></div>
<button onclick="playHandler()">开始</button>
<button onclick="pauseHandler()">暂停</button>
<script>
const box = document.querySelector(".box")
const keyframes = [
{ right: 0 },
{ right: '100px' },
];
const opts = {
duration: 1000,
iterations: 1,
direction: 'alternate',
easing:'ease-in-out',
fill: "forwards",
}
function playHandler() {
const animation = box.animate(keyframes, opts);
animation.play();
}
</script>
</body>
</html>
