动画触发事件
当元素使用 animation 样式产生动画效果时,会触发 animationstart、animationend、animationiteration 和 animationcancel 等相关事件 ( event ),这些事件可以透过 JavaScript 接收并进行对应的动作,这篇教学会介绍这些 animation 的触发事件,以及使用 CSSKeyframesRule 修改进行中的动画样式。
快速导览:
animation 触发的事件
元素使用 animation 样式产生动画效果时,在动画进行过程中会触发下列四种事件:
| 事件 | 触发时机 |
|---|---|
| animationstart | 动画开始时。 |
| animationend | 动画结束时。 |
| animationiteration | 动画重复时。 |
| animationcancel | 动画中止时 ( 少部分浏览器不支援 )。 |
使用 JavaScript 读取 animation 触发事件
元素 animation 触发的事件无法在 CSS 里操作,必须透过 JavaScript 才能读取,下方范例会使用 JavaScript 读取四种触发事件,当动画开始时会出现“start”,每当动画重复一次就会出现“重复次数”,动画结束后会出现“end”,若动画进行到一半终止 ( 鼠标移开造成中止 ),就会出现“cancel”。
<!-- HTML 程式碼-->
<h2>滑鼠移動到我上方</h2>
<h3>動畫狀態:<span></span></h3>
<div></div>
<!-- CSS 程式碼 -->
<style>
h2 {
width: 300px;
border: 2px solid #000;
}
h2:hover~div {
animation-name: oxxo;
animation-duration: 2s;
animation-iteration-count: 3;
}
div {
width: 50px;
height: 50px;
margin:5px;
background: red;
}
@keyframes oxxo{
50% {margin-left: 200px;}
}
</style>
<!-- JS 程式碼 -->
<script>
const msg = document.querySelector('span');
const d = document.querySelector('div');
let num = 0;
d.addEventListener("animationstart", () => {
msg.innerHTML = "start";
});
d.addEventListener("animationend", () => {
msg.innerHTML = "end";
});
d.addEventListener("animationiteration", () => {
num = num + 1;
msg.innerHTML = `重複 ${num} 次`;
});
d.addEventListener("animationcancel", () => {
msg.innerHTML = "cancel";
});
</script>
CSSKeyframesRule
浏览器有一个很好用的功能:“网页开发者工具”,可以透过这个功能查看 document 的 styleSheets 属性,这个属性会将网页里所有用到的样式列出,举例来说,打开任何一网页后打开网页开发者工具,在 console 输入 document.styleSheets,就会看到网站使用的所有 CSS。
如果网页中使用下方范例制作简单动画,打开网页后打开网页开发者工具,在 console 输入 document.styleSheets,就能看到 CSSKeyframesRules 动画规则,以及 CSS 中对于这个动画的所有设定。
<!-- HTML 程式碼-->
<div></div>
<!-- CSS 程式碼 -->
<style>
div {
width: 50px;
height: 50px;
margin:5px;
animation-name: oxxo;
animation-duration: 2s;
animation-iteration-count: infinite; /* 動畫無限播放 */
background: red;
}
@keyframes oxxo{
33% {background: #0a0;}
50% {margin-left: 200px;}
66% {background: #06f;}
}
</style>
透过下列三种 JavaScript 的方法就可以修改动画内容,下方的范例会在网页打开的时候,点击按钮后会移除原本 50% 的 keyframe 并添加新的 50% keyframe,在“动画不中断”的情况下,修改动画样式。
| 方法 | 说明 |
|---|---|
findRule() |
找出对应规则 |
appendRule() |
添加规则 |
deleteRule() |
删除规则 |
<!-- HTML 程式碼-->
<button>更換動畫內容</button>
<div></div>
<!-- CSS 程式碼 -->
<style>
div {
width: 50px;
height: 50px;
margin:5px;
animation-name: oxxo;
animation-duration: 2s;
animation-iteration-count: infinite; /* 動畫無限播放 */
background: red;
}
@keyframes oxxo{
33% {background: #0a0;}
50% {margin-left: 200px;}
66% {background: #06f;}
}
</style>
<!-- JS 程式碼 -->
<script>
const btn = document.querySelector('button');
const keyframes = document.styleSheets[0].cssRules[1];
btn.addEventListener('click',function(){
keyframes.deleteRule('50%');
keyframes.appendRule('50% {margin-top: 100px;}');
});
</script>
小结
由于操控事件需要具有一些 JavaScript 的基础,没有办法单纯依靠 CSS 就实现,不过 animation 事件是辅助动画相当实用的技巧,如果有机会,不妨替网页动画增加一些事件机制,做出更有意思的效果。
微信扫码关注
抖音扫码关注