【发布时间】:2018-11-20 09:24:39
【问题描述】:
我在 JS 和 CSS 中更改循环淡入/淡出图像源并使用 SetTimeout() 回调时遇到问题。 问题是,序列的工作方式很奇怪:有时图像在过渡开始之前就发生了变化,有时它工作正常,有时则相反。
这是我的 JS:
const animationTime = 5000;
const transitionTime = 500;
function nextImage() {
let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-transitionTime);
img.src=randomize();
setTimeout(nextImage, animationTime);
}
- randomize() 函数只是从数组中获取一个随机的图像路径。
这里是 HTML:
<div class="some-class">
<img class="some-image" id="img1" src="1.png">
</div>
这里是 CSS:
.some-image {
transition: opacity 0.5s linear;
-webkit-transition: opacity 0.5s linear;
-o-transition: opacity 0.5s linear;
-moz-transition: opacity 0.5s linear;
-moz-border-radius: 15px;
}
.hidden {
opacity: 0;
}
更新。 所以我编辑了 CSS 文件:
.some-image {
width: 370px;
height: 190px;
animation: fade-out;
animation-duration: 1s;
}
.hidden {
animation: fade-out;
animation-duration: 1s;
}
@keyframes fade-in {
from {opacity: 0;}
to {opacity: 1;}
}
@keyframes fade-out {
from {opacity: 1}
to {opacity: 0}
}
还有 JS 文件:
function nextImage() {
let img = document.getElementById('img1');
img.classList.remove('hidden');
setTimeout(function () {
img.classList.add('hidden');
},animationTime-1000);
img.src=randomize();
}
setTimeout(nextImage, animationTime);
}
而且,不知何故,它在本地机器上完美运行,但在专用网站上,动画有时会在图像源更改之前淡入。
【问题讨论】:
-
你能提供暴露问题的工作小提琴吗? jsfiddle.net
标签: javascript html css css-transitions settimeout