这段代码应该在单击#topbar时展开#bottombar,并在#bottombar高度为200px时隐藏它,但行为很奇怪。这是为什么?
<!DOCTYPE html>
<html>
<style>
#wire {
display: block;
}
#topbar {
background-color: rgba(240,240,240,1);
cursor: pointer;
}
#bottombar {
height: 0px;
overflow: hidden;
background-color: rgba(210,210,210,1);
}
</style>
<body>
<div id = "wire">
<div id = "topbar" onClick = "expand()">Stuff</div>
<div id = "bottombar">Other stuff</div>
</div>
</body>
<script>
function expand() {
var timing = {
duration: 400,
fill: "forwards",
easing: "ease-out"
}
var bottombar = document.getElementById('bottombar')
if (bottombar.style.height == 0) {
bottombar.animate([{height: "0px"},{height: "200px"}], timing);
} else if (bottombar.style.height !== 0) {
bottombar.animate([{height: "200px"},{height: "0px"}], timing);
}
}
</script>
</html>
最佳答案
我想我在这里看到了你的问题。 element.style 与其当前样式之间存在区别。 This answer稍微解决了这个区别。
这里是the Mozilla Developer's Network Article on getComputedStyle
这是查看当前样式的代码,我很确定这就是您想要的。
function expand() {
var timing = {
duration: 400,
fill: "forwards",
easing: "ease-out"
}
var bottombar = document.getElementById('bottombar')
var bottombarComputedStyles = window.getComputedStyle(bottombar);
var bottombarHeight = bottombarComputedStyles.getPropertyValue('height');
if (bottombarHeight == "0px" || bottombarHeight == "0") {
console.log(`height is 0 or 0px`);
bottombar.animate([{height: "0"},{height: "200px"}], timing);
} else {
console.log(`height is neither 0 nor 0px. It is ${bottombarHeight}`);
bottombar.animate([{height: "200px"},{height: "0"}], timing);
}
}
#wire {
display: block;
}
#topbar {
background-color: rgba(240,240,240,1);
cursor: pointer;
}
#bottombar {
height: 0px;
overflow: hidden;
background-color: rgba(210,210,210,1);
}
<div id = "wire">
<div id = "topbar" onClick = "expand()">Stuff</div>
<div id = "bottombar">Other stuff</div>
</div>
关于javascript - 为什么这个反转条件动画不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61468686/