- 最近朋友问了这样的问题:css高度从0 到auto过渡,上拉或者收起
主要利用 - scrollHeight:scrollHeight
- transition:transition
- maxHeight:maxHeight
应用场景:点击收起、下拉 然后进行过渡,开发中应该经常会遇到这样的需求
直接上代码:
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style>
#el {
overflow: hidden;
max-height: 0;
background: darkgoldenrod;
transition: max-height 0.5s;
}
</style>
<body>
<div class="trigger">
<button onclick="myFunction()">确定</button>
<div id="el">contentcontentcontentcontentcontentcontentcontent
<p>
content
</p>
<p>
contentcontent
</p>
<p>
contentcontent
</p>
</div>
</div>
</body>
<script>
function myFunction() {
let el = document.getElementById('el');
let height = el.scrollHeight;
if(el.style.maxHeight=='0px' || el.style.maxHeight=='') {
el.style.maxHeight=`${height}px`;
}else {
el.style.maxHeight=`0px`;
}
}
</script>
</html>