4 回答

TA貢獻1784條經驗 獲得超7個贊
我認為添加class
是一種健康的方式。
檢查此處的示例:https ://codepen.io/yasgo/pen/zYBgjXN
document.getElementById('box').classList.add('active-animation');
.box {
width: 50px;
height: 50px;
background-color: black;
}
.box.active-animation {
animation: party 5s infinite;
}
@keyframes party{
0% {background-color: red;}
10% {background-color: orange;}
20% {background-color: yellow;}
30% {background-color: green;}
40% {background-color: blue;}
50% {background-color: purple;}
}
<div id="box" class="box"></di>

TA貢獻1871條經驗 獲得超13個贊
這比你想象的要容易得多,你只需要調用動畫,就像這樣:
這是使用按鈕觸發的示例
function party(){
document.body.style.animation = 'party 2.5s infinite linear';
}
body{
background-color: purple;
}
@keyframes party{
0% {background-color: red;}
10% {background-color: orange;}
20% {background-color: yellow;}
30% {background-color: green;}
40% {background-color: blue;}
50% {background-color: purple;}
}
@-webkit-keyframes party{
0% {background-color: red;}
10% {background-color: orange;}
20% {background-color: yellow;}
30% {background-color: green;}
40% {background-color: blue;}
50% {background-color: purple;}
}
<html>
<body id="bd">
<button onclick="party()">Press Me!</button>
</body>
</html>
我等著這可以幫助你!

TA貢獻1982條經驗 獲得超2個贊
var box = document.getElementById('box');
box.style.animation = "party 5s infinite";
#box {
width: 200px;
height:150px;
background-color: black;
margin: 20px auto;
border-radius: 5px;
}
@keyframes party{
0% {background-color: red;}
10% {background-color: orange;}
20% {background-color: yellow;}
30% {background-color: green;}
40% {background-color: blue;}
50% {background-color: purple;}
}
@-webkit-keyframes party{
0% {background-color: red;}
10% {background-color: orange;}
20% {background-color: yellow;}
30% {background-color: green;}
40% {background-color: blue;}
50% {background-color: purple;}
}
<div id="box"></div>

TA貢獻1812條經驗 獲得超5個贊
您可以設置animation要設置動畫的元素的屬性,如下所示。
// sets the css animation property
const spinner = document.getElementById("spinner");
spinner.style.animation = "spin 3s linear infinite";
/* gives the div element a border and size */
#spinner {
border: 15px solid black;
border-top: 15px solid white;
border-bottom: 15px solid white;
border-radius: 50%;
width: 50px;
height: 50px;
/* no animation property is inserted here */
}
/* spin animation */
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
<!-- div element to animate -->
<div id="spinner"></div>
添加回答
舉報