<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="toggleHeight()">点击我切换高度</button>
<div class="box">tips:dwqdqwwdqwdqwdqwdqwd</div>
<style>
.box {
background-color: #ccc;
transition: height 0.5s ease-in-out;
overflow: hidden;
}
</style>
<script>
let originHeight = null;
init()
function init(){
var box = document.querySelector(".box");
var height = box.clientHeight;
originHeight = height;
box.style.height = "0px";
}
function toggleHeight() {
var box = document.querySelector(".box");
if (box.style.height !== "0px") {
box.style.height = "0px";
} else {
box.style.height = originHeight + "px";
}
}
</script>
</body>
</html>
首先,css height过渡,必须设置具体数值,如果设置auto,呢么过渡效果不会产生,所以需要使用js获取,以此来获取高度值,然后保存起来originHeight,切换时候设置height为0px或者originHeight来切换实现过渡效果。
ps:可能有伙伴会问,呢上面的例子和height:auto有什么关系,需要注意height的默认值就是auto;