第一次单击该按钮时,淡入淡出动画(更改不透明度)会起作用。但是对于下一步的所有点击,它不再起作用。当我进行调试时,它显示它每次都在工作。但在现实中,为什么不呢?
let colorArray = ['red','yellow','green','teal']
let index = 0
function imageChanger(){
document.querySelector('.container').id = ''
if(index == colorArray.length-1) index = 0
else index++
document.querySelector('.container').style.backgroundColor = colorArray[index]
document.querySelector('.container').id = 'fade'
}.container{
height: 300px;
max-width: 400px;
background-color: teal;
}
#fade{
animation: fade 5s;
}
@keyframes fade{
from{opacity:.4 }
to{opacity: 1}
}<button onclick="imageChanger()">Change</button>
<div class="container" id=""></div>
发布于 2020-04-12 00:47:06
我基本上同意上面的答案。我只想指出,如果你想让第一个青色块显示为青色,而不是不透明的,你需要在你的初始html中包含fade类。
此外,如果您希望第一个转换为青色到红色,则应该从索引位置-1开始,而不是0。
<button onclick="imageChanger()">Change</button>
<div class="container fade" id=""></div>
let index = -1;发布于 2020-04-12 00:04:39
一旦你添加了fade id,它就运行动画并且不再重复。
您应该每次都将其删除,然后重新添加。使用setTimeout让css有时间来发现它被移除了。
另外,我建议使用class代替id,使用过渡代替关键帧。
let colorArray = ['red','yellow','green','teal']
let index = 0
function imageChanger(){
document.querySelector('.container').id = ''
if(index == colorArray.length-1) index = 0
else index++
document.querySelector('.container').style.backgroundColor = colorArray[index]
document.querySelector('.container').classList.remove('fade')
setTimeout( function(){ document.querySelector('.container').classList.add('fade')
}, 50);
}.container{
height: 300px;
max-width: 400px;
background-color: teal;
opacity: .2;
transition: opacity 0s linear;
}
.container.fade{
transition: opacity 3s linear;
opacity: 1;
}<button onclick="imageChanger()">Change</button>
<div class="container fade"></div>
https://stackoverflow.com/questions/61159572
复制相似问题