【问题标题】:Clicking a button to initiate an animation, then clicking another button to revers that animation单击一个按钮以启动动画,当单击另一个按钮以反转该动画时
【发布时间】:2021-05-06 06:25:46
【问题描述】:

我创建了一个按钮,您可以在其中单击它。然后它会启动一个 CSS 动画,其中一些按钮和文本沿着屏幕向下流动,说你确定要这样做吗?然后他们可以单击是或否按钮,我希望它可以反转动画。我已经完成了向下的动画,但是当他们单击按钮时,我无法重复该动画返回。

这是 HTML:

<button onclick="confirm()">Delete</button>

<div id="wholeshow" class="confirm-whole">
    <h1 class="confirm">Delete</h1>
    <p class="confirm">Are you sure you want to delete ____?</p>
    <button class="confirm" onclick="reset()">Delete</button>
    <button class="confirm" onclick="cancel()">Cancel</button>
</div>

这里是 JS:

function confirm() {

document.getElementById("wholeshow").classList.add("add");
}

这里是 CSS:

.confirm-whole {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: grey;
    animation: slideIn 0.5s forwards;
}

@keyframes slideIn {

    0% {
        top: -250px;
        height: 0%;
    }

    99% {
        height: 0%;
    }

    100% {
        top: 0px;
        height: 100%;
    }
}

.add {
    display: block;
}

非常感谢您的帮助!

【问题讨论】:

标签: javascript html css


【解决方案1】:

JavaScript 不是很漂亮,但它可以工作,如果 CSS 过渡能够支持您的动画要求,也许更好的解决方案是使用它们。

function confirm() {
  document.getElementById("wholeshow").classList.add("add");
}

// added
function reset() {
  const wholeshow = document.getElementById("wholeshow");
  const resetDir = () => { // need to reset the animation direction and remove the `add` class
    wholeshow.removeEventListener("animationend", resetDir, true);
    wholeshow.style.animationDirection = "normal";
    wholeshow.classList.remove("add");
  };

  wholeshow.addEventListener("animationend", resetDir, true);
  wholeshow.style.animationDirection = "reverse";
  wholeshow.classList.remove("add");
  void wholeshow.offsetWidth; // force rerender
  wholeshow.classList.add("add");
}
.confirm-whole {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: grey;
  animation: slideIn 0.5s;
}

@keyframes slideIn {
  0% {
    top: -250px;
    height: 0%;
  }
  99% {
    height: 0%;
  }
  100% {
    top: 0px;
    height: 100%;
  }
}

.add {
  display: block;
}
<button onclick="confirm()">Delete</button>

<div id="wholeshow" class="confirm-whole">
  <h1 class="confirm">Delete</h1>
  <p class="confirm">Are you sure you want to delete ____?</p>
  <button class="confirm" onclick="reset()">Delete</button>
  <button class="confirm" onclick="cancel()">Cancel</button>
</div>

【讨论】:

    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多