[英]Why this invert conditional animation does not work?
This piece of code is supposed to expand the #bottombar when #topbar is clicked and hide it while the #bottombar height is 200px, but acts strangely.这段代码应该在单击#topbar 时展开#bottombar,并在#bottombar 高度为200px 时隐藏它,但行为很奇怪。 Why is that?
这是为什么?
<!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>
I think I see your problem here.我想我在这里看到了你的问题。 There's a distinction between element.style and its current style.
element.style 与其当前样式之间存在区别。 This answer addresses that distinction a bit.
这个答案稍微解决了这种区别。
Here is the Mozilla Developer's Network Article on getComputedStyle这是Mozilla 开发人员关于 getComputedStyle 的网络文章
Here is your code looking at the current style, which I am pretty sure is what you want.这是您查看当前样式的代码,我很确定这是您想要的。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.