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>
添加回答
举报