为什么这种反向条件动画不起作用?

问题描述 投票:0回答:1

[这段代码应该在单击#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>
javascript jquery-animate
1个回答
1
投票

我想我在这里看到您的问题。 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>
© www.soinside.com 2019 - 2024. All rights reserved.