- 最近朋友问了这样的问题: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>

本文介绍了一种使用CSS实现元素高度从0过渡到自动高度的方法,通过scrollHeight、transition和maxHeight属性,实现了点击按钮时元素的优雅展开与收起效果。代码示例展示了如何在HTML中设置样式及JavaScript交互。
589

被折叠的 条评论
为什么被折叠?



