js控制css的animation動畫
阿新 • • 發佈:2021-12-05
昨天寫作業想要實現通過點選觸發animation動畫的效果。想了很久發現可以用js修改css,不過我並沒有直接掌握keyframes裡的內容的技術(哭死)。所以我的解決思路是寫兩份css,一份是初始狀態,一份是觸發後需要顯示的效果,但在實際操作中發現直接替換css檔案後不知道為什麼動畫效果並不會實現,只能顯示動畫結束時的狀態。後面我改變了做法,直接修改css內容。
例項:
html檔案
<!DOCTYPE html> <html> <head> <link rel="stylesheet" src="index.css" type="text/css"> <script type="text/javascript" src="control.js"></script> </head> <body> <div id="pic" class="pic1"> <img src="pic.jpg"> </div> <button type="button" onclick="next()">start</button> </body> </html>
css檔案
.pic1{ /*初始狀態*/ position: relative; width:50%; top:50%; } /*動畫*/ .pic2{ position: relative; width:50%; top:50%; animation-name: pic2; animation-duration: 3s; animation-fill-mode: both; } @-webkit-keyframes pic2{ /*適用於chrome*/ 0% { width:90%; top:50%; } 50%{ width:50%; top:50%; } 100% { width:50%; top:10%; } }
js程式碼
function next(){
document.getElementById("pic").className="pic2";
}
這樣就實現了對animation的控制。