在转到下一步之前强制JavaScript完成动画

问题描述 投票:0回答:2

我正在建立一个简单的旋转器,为网站旋转三条建议。我想让它淡出/添加/删除类来做到这一点。在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;
}
javascript css css3 css-transitions
2个回答
3
投票

您可以使用其transitionend事件来获得更准确的切换。

堆栈代码段

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>

另一种选择是使用animation,用它可以做更酷的东西。

这是我的另一个答案,有一个简单的样本:


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");});

}
© www.soinside.com 2019 - 2024. All rights reserved.