irpas技术客

实现div盒子的高度随页面内容增多而变化(自适应高度)效果_weixin_46353030

网络 5193

一、功能需求:

给三个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://·/cssref/pr-dim-max-height.html


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #保持三个div盒子的布局