javascript - css关键帧动画反转

标签 javascript html css css-animations

我试图在页面顶部隐藏一个大的内容,当用户单击该按钮时,它会向下滑动,如果用户再次单击该按钮,它会向上滑动,等等。我不太确定为什么会这样不起作用,有什么想法吗?

document.getElementById("button").addEventListener("click", function() {
  var x = document.getElementById("one");
  if (x.style.animation === "shrink .8s") {
    x.style.animation = "shrink .8s";
  } else {
    x.style.animation = "expand .8s";
  }
});
#one {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: black;
  animation: shrink .8s;
  animation-fill-mode: forwards;
  
  z-index: -1;
}

@keyframes expand {
  100% {
    top: 0;
  }
}

@keyframes shrink {
  100% {
    top: -100vh
  }
}
<button id="button">Click</button>

<div id="one"></div>

最佳答案

问题是,当您更改动画时,它将从元素的初始状态开始考虑,而不是前一个动画的最终状态。因此,使用动画您不会获得预期的结果(即使我们更正您的 JS 代码,因为这不是测试动画的正确方法)

document.getElementById("button").addEventListener("click", function() {
  var x = document.getElementById("one");
  x.classList.toggle('expand');
});
#one {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: black;
  animation: shrink .8s;
  animation-fill-mode: forwards;
  z-index: -1;
}

#one.expand {
  animation: expand .8s;
}

@keyframes expand {
  100% {
    top: 0;
  }
}

@keyframes shrink {
  100% {
    top: -100vh
  }
}
<button id="button">Click</button>

<div id="one"></div>

在这种情况下,最好通过切换单个类来更改 top 属性来使用转换:

document.getElementById("button").addEventListener("click", function() {
  var x = document.getElementById("one");
  x.classList.toggle('expand')
});
#one {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: black;
  top: -100vh;
  transition: all 1s;
  z-index: -1;
}

#one.expand {
  top: 0;
}
<button id="button">Click</button>

<div id="one"></div>

关于javascript - css关键帧动画反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50306288/

相关文章:

javascript - 从对象集中获取三个值

javascript - jquery attr ('checked' ,'checked' ) 只工作一次

javascript - 获取在 JavaScript 函数中的 DatePicker 中选择的日期

css - 将 div 垂直和水平居中

html - IE11 CSS - 悬停某些链接时导航 div 移动

php - 在php中删除行

css - 将 flexbox 元素与 block 中最后一个文本行的基线对齐

javascript - 如何限制一个元素在一分钟内被点击的次数?

php - 如何获得实时更新?

javascript - 使用 css 在 slider 的中心插入图形