我想用 JavaScript 函数更改 CSS 类的动画属性。我一直在尝试各种方法,但都没有奏效。请找出我哪里出错了。
CSS:
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
border-radius: 50%;
background: transparent;
}
.center .earth {
position: absolute;
top: 0;
width: 200px;
height: 200px;
background-image: url(https://www.publicdomainpictures.net/pictures/90000/velka/earth-map.jpg);
margin: 3em auto;
border-radius: 50%;
background-size: 630px;
animation: spin 30s linear alternate infinite;
box-shadow: inset 20px 0 80px 6px rgba(0, 0, 0, 1);
color: #000;
}
.center .earth .moon {
position: absolute;
top: calc(50% - 1px);
left: 50%;
width: 200px;
height: 2px;
transform-origin: left;
border-radius: 50%;
animation: rotate 10s linear infinite;
}
.center .earth .moon::before {
content: '';
background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRsvjrANMGI8aBJSFbsHteVa04rcB1IjjNsbrhm8vTLflfpiG133g);
position: absolute;
background-size: 200px;
top: -25px;
right: 0;
width: 50px;
height: 50px;
border-radius: 50%;
animation: spin 10s linear infinite;
}
@keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes spin {
100% {
background-position: 100%;
}
}
HTML:
<div className="center">
<div className="earth">
<div className="moon" />
</div>
</div>
JavaScript 函数:
function change() {
var elem = document.getElementsByClassName('moon');
elem.style.animation="rotate 5s linear infinite";
}
我尝试了各种方法,但都无法进行修改。遍历对象也无济于事。
最佳答案
elem
是元素的 HTMLCollection,而不是单个元素,设置 HTMLCollection 的 style
属性不起作用。
相反,您需要单独更改每个元素的样式:
Array.from(document.getElementsByClassName('moon')).forEach(elem => {
elem.style.animationDuration = "5s";
});
编辑:
这里有一个片段可以证明该方法有效/提供引用:
function change_spin_rate() {
Array.from(document.getElementsByClassName('spinner')).forEach(elem => {
elem.style.animationDuration = "1s";
});
}
document.getElementById("spin_change").onclick = change_spin_rate;
@keyframes spin {
from {
transform: rotate(360deg);
}
to {
transform: rotate(0deg);
}
}
.spinner {
display: inline-block;
animation: spin 4s infinite linear;
}
#spin_change {
padding: 8px 16px;
display: inline-block;
font-family: sans-serif;
cursor: pointer;
border-radius: 16px;
}
#spin_change:hover {
background: rgba(0, 64, 255, 0.1);
}
<a class="spinner">🌀</a><a class="spinner">🌀</a><a class="spinner">🌀</a>
<a id="spin_change">Click me to change the spin rate for all spinners.<a>
<a class="spinner">🌀</a><a class="spinner">🌀</a><a class="spinner">🌀</a>
关于javascript - 使用 JavaScript 更改带有类名的 div 的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50901006/