javascript - 为什么这个反转条件动画不起作用?

标签 javascript jquery-animate

这段代码应该在单击#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/

相关文章:

javascript - 如何根据高度平移图像?

javascript - 如何使用复选框显示/隐藏 HTML 元素

jquery - 使用 Velocity.js 或 Transit.js 来实现 CSS/JS/jQuery 动画?

jquery - 展开div,固定在右中心点

jquery - 动画飞机穿过屏幕

javascript - 根据值更改 jquery.animate

javascript - 谷歌关闭 : goog. require 找不到 : goog. ui

javascript - 我可以改进这个 jQuery 代码重复吗?

javascript - 如何使用窗口覆盖和多个拖放区处理文件拖放?

javascript - jQuery animate 在 Canvas 上移动文本