您好,我在这里尝试使用css动画更改灯光的颜色。我使用的方法是使用js添加/删除动画类。 选择一个不同的按钮可以正常工作,但是单击同一按钮两次则无法工作。如何解决?
postgresql:
image: orchardup/postgresql
environment:
- "POSTGRESQL_PASS=***"
labels:
- "traefik.enable=true"
- "traefik.frontend.rule=Path:/postgresql/"
function getElement(k){
var elm = document.getElementById(k);
return elm;
}
function OnLight(j){
getElement("light" + j).classList.add('buttonAnim');
}
function resetLight(){
for(let k=1 ; k<=3 ; k++){
if ( getElement("light" + k).classList.contains('buttonAnim') ){
getElement("light" + k).classList.remove('buttonAnim');
}
}
}
for(let i=1 ; i<=3 ; i++){
getElement("button" + i).addEventListener("click",function(){
resetLight();
OnLight(i);
});
}
li{
list-style:none;
}
.light {
width: 45px;
height: 45px;
border-radius: 50%;
border: 1px solid #000;
background-color: #611114;
box-shadow: inset 0px 0px 5px 1px #000;
}
.buttonAnim {
-webkit-animation-name: lightChanger;
-webkit-animation-duration:5s;
-webkit-animation-iteration-count: 1;
-webkit-animation-timing-function: ease;
-webkit-animation-fill-mode: forwards;
}
@-webkit-keyframes lightChanger {
0% {background-color: #611114;}
40% { background-color: #da0d17;}
60% { background-color: #da0d17;}
100% {background-color: #611114;}
}
答案 0 :(得分:2)
由于您的动画基于类,因此您需要重新调用该类以在单击同一按钮时再次制作动画,在这里,我已经更新了您的js代码:
function getElement(k){
var elm = document.getElementById(k);
return elm;
}
function OnLight(j){
getElement("light" + j).classList.remove('buttonAnim');
setTimeout(function(){
getElement("light" + j).classList.add('buttonAnim');
},10);
}
function resetLight(){
for(let k=1 ; k<=3 ; k++){
if ( getElement("light" + k).classList.contains('buttonAnim') ){
getElement("light" + k).classList.remove('buttonAnim');
}
}
}
for(let i=1 ; i<=3 ; i++){
getElement("button" + i).addEventListener("click",function(){
resetLight();
OnLight(i);
});
}
li{
list-style:none;
}
.light {
width: 45px;
height: 45px;
border-radius: 50%;
border: 1px solid #000;
background-color: #611114;
box-shadow: inset 0px 0px 5px 1px #000;
}
.buttonAnim {
-webkit-animation-name: lightChanger;
-webkit-animation-duration:5s;
-webkit-animation-iteration-count: 1;
-webkit-animation-timing-function: ease;
-webkit-animation-fill-mode: forwards;
}
@-webkit-keyframes lightChanger {
0% {background-color: #611114;}
40% { background-color: #da0d17;}
60% { background-color: #da0d17;}
100% {background-color: #611114;}
}
<li>
<button id="button1" class="button">button1</button>
<div id="light1" class="light"></div>
</li>
<li>
<button id="button2" class="button">button2</button>
<div id="light2" class="light"></div>
</li>
<li>
<button id="button3" class="button">button3</button>
<div id="light3" class="light"></div>
</li>
希望这会对您有所帮助。