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