我正在构建一个简单的旋转器,为网站旋转三条建议。我想让它淡出/添加/删除类来做到这一点。在JavaScript调试器中,它工作得很好,因为它有时间来执行所有调用,但在实际执行中,它非常不稳定。我理解它是这样做的,因为脚本只关心添加类,它并不关心在类中完成转换,但我需要知道如何让脚本完全完成转换班级。这是JavaScript:
function rotateAdvice() {
let nextAdvice;
const currentAdviceCont = document.querySelector(".advice-show");
const currentAdvice = currentAdviceCont.id.slice(-1);
if (currentAdvice >= 2) {
nextAdvice = document.getElementById("advice-0");
} else {
nextAdvice = "advice-"+(parseInt(currentAdvice) + 1);
nextAdvice = document.getElementById(nextAdvice);
}
currentAdviceCont.classList.add("advice");
currentAdviceCont.classList.remove("advice-show");
currentAdviceCont.classList.add("no-display");
nextAdvice.classList.remove("no-display");
nextAdvice.classList.add("advice-show");
}
// called through this:
setInterval(rotateAdvice, 4000);
以下是三个css类:
.advice {
opacity: 0;
transition: 1s opacity;
}
.advice-show {
opacity: 1;
transition: 1s opacity;
}
.no-display {
display: none;
visibility: hidden;
}
答案 0 :(得分:3)
您可以使用其transitionend
事件来获得更准确的切换。
Stack snippet
var box1 = document.querySelector(".box.nr1");
var box2 = document.querySelector(".box.nr2");
box1.addEventListener("transitionend", trans_ended, false);
box2.addEventListener("transitionend", trans_ended, false);
setTimeout(function() { box1.classList.add('trans') }, 10);
function trans_ended (e) {
if (e.type == 'transitionend') {
if (e.target == box1) {
box1.classList.remove('trans');
setTimeout(function() { box2.classList.add('trans') }, 10);
} else if (e.target == box2) {
box2.classList.remove('trans');
setTimeout(function() { box1.classList.add('trans') }, 10);
}
}
}

.box {
position: absolute;
left: 1em;
top: 1em;
width: 5em;
height: 5em;
background-color: blue;
opacity: 0;
transition: opacity 2s;
}
.box.nr2 {
background-color: red;
}
.box.trans {
opacity: 1;
}

<div class="box nr1"></div>
<div class="box nr2"></div>
&#13;
另一个选择是使用animation
,可以使用哪个更酷的东西。
这是我的另一个答案,只有一个简单的样本:
答案 1 :(得分:0)
我刚刚使用了一个简单的事件监听器来实现transitionend:
currentAdviceCont.classList.add("advice");
currentAdviceCont.classList.remove("advice-show");
currentAdviceCont.addEventListener("transitionend", () => {
currentAdviceCont.classList.add("no-display");
nextAdvice.classList.remove("no-display");
nextAdvice.classList.remove("advice");
nextAdvice.classList.add("advice-show");});
}