一、功能需求:
给三个div盒子,实现对处于中间的div盒子隐藏多余内容。此时配置一个show按钮,当点击show按钮后将被隐藏的内容显示出来,并令后一个div盒子向下移动适当距离。保持三个div盒子的布局。


二、实现核心
方法在于max-height属性、overflow属性和display:inline-block属性
三、具体实现:
- 对中间的div设置一个max-height高度+overflow:hidden属性+display:inline-block属性;
- 用js获取show按钮和处于中间的div盒子;
- 当点击show按钮时,将max-height修改为none,overflow修改为visible;
代码实现:
//css文件
.middle {
display: inline-block;
overflow: hidden;
max-height: 200px;
background-color: skyblue;
}
//js文件
var show = document.querySelector('.show');
var middle = document.querySelector('.middle');
show.onclick = function () {
middle.style.overflow = 'visible';
middle.style.maxHeight = 'none';
}
最终效果:

这里我用了include盒子装2号盒子,去掉include盒子也能实现布局不乱的效果,但是2号盒子的高度不会变。加个include盒子,使其高度设置为auto,此时include的高度就是随着2号盒子内容的变化而变化的了。
.include {
width: 400px;
height: auto;
background-color: tan;
}
四、完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div {
width: 200px;
height: 200px;
}
.first {
background-color: pink;
}
.include {
width: 400px;
height: auto;
background-color: tan;
}
.middle {
display: inline-block;
overflow: hidden;
max-height: 200px;
background-color: skyblue;
}
.last {
background-color: slateblue;
}
.show {
margin: 10px;
width: 100px;
height: 30px;
border: 2px;
outline: none;
background-color: green;
cursor: pointer;
}
</style>
<body>
<div class="first">我是1号盒子</div>
<div class="include">
<div class="middle">
我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子我是2号盒子
</div>
</div>
<button class="show">显示按钮</button>
<div class="last">我是3号盒子</div>
</body>
<script>
var show = document.querySelector('.show');
var middle = document.querySelector('.middle');
show.onclick = function () {
middle.style.overflow = 'visible';
middle.style.maxHeight = 'none';
}
</script>
</html>
五、参考资料
max-height属性详解
https://www.runoob.com/cssref/pr-dim-max-height.html
本文介绍了如何使用CSS的max-height、overflow和display属性,配合JavaScript实现div盒子高度随内容增减自适应的效果。通过设置中间div的max-height和overflow属性,并在点击show按钮时调整这些属性,保持布局的稳定性。完整代码和max-height属性详解链接提供参考。
4万+

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



