当前位置: 首页 > java >正文

前端让一个div的高度为屏幕的高度减去其他所有元素的高度(包括它们的margin和padding),并自适应。

前端让一个div的高度为屏幕的高度减去其他所有元素的高度(包括它们的margin和padding),并自适应。

项目需求是让.adaptive-height的高度在不同的移动端中高度自适应。

![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/a8c6311cfba34a1481ae898f78e45adc.pn

template

    <div class="bigBox"><div class="title1"></div><div class="title1"></div><div class="languageSwitch"></div><div class="notesMsg"></div><div class="tijiao"></div></div>

方法一、js

onMounted(() => {// 初始设置setAdaptiveHeight();// 窗口大小变化时重新计算window.addEventListener("resize", setAdaptiveHeight);
});// 设置CSS变量
function calculateTotalHeight(elements) {let totalHeight = 0;elements.forEach((element) => {const el = document.querySelector(element);if (el) {const style = window.getComputedStyle(el);const height = el.offsetHeight;const marginTop = parseFloat(style.marginTop) || 0;const marginBottom = parseFloat(style.marginBottom) || 0;const paddingTop = parseFloat(style.paddingTop) || 0;const paddingBottom = parseFloat(style.paddingBottom) || 0;totalHeight += height + marginTop + marginBottom + paddingTop + paddingBottom;}});return totalHeight;
}function setAdaptiveHeight() {// 选择所有需要计算高度的元素(使用CSS选择器)const elementsToMeasure = [".title1",".title1",".languageSwitch",".notesMsg",".tijiao",]; // 添加更多元素选择器const totalHeight = calculateTotalHeight(elementsToMeasure);const adaptiveDiv = document.querySelector(".adaptive-height");if (adaptiveDiv) {adaptiveDiv.style.height = `calc(96vh - ${totalHeight}px)`;//我的.bigBox是96vh,这里可以自己按div的高度来取值}
}

说明

calculateTotalHeight函数:这个函数接收一个元素选择器数组,遍历每个元素,计算其总高度(包括内容高度、margin和padding)。
setAdaptiveHeight函数:这个函数使用上述计算的总高度来设置自适应div的高度。
事件监听器:添加了窗口大小变化的事件监听器,以便在窗口大小改变时重新计算高度。

注意事项

确保在elementsToMeasure数组中包含所有需要计算高度的元素的选择器。
如果页面中有动态内容(例如,元素高度会变化),需要在内容变化后调用setAdaptiveHeight函数。
这种方法考虑了margin和padding,确保计算的高度是精确的。
对于复杂的布局,可能需要进一步调整计算逻辑。

这种方法提供了最大的灵活性,可以处理分散在页面各处的多个元素的高度计算。

方法二:css

.bigBox {display: flex;flex-direction: column;height: 94vh;
}
.adaptive-height {flex: 1; /* 占据剩余空间 */overflow: auto; /* 如果内容超出,添加滚动条 */
}
http://www.xdnf.cn/news/1830.html

相关文章:

  • Python笔记:VS2013编译Python-3.5.10
  • 芯岭技术XL32F003单片机 32位Cortex M0+ MCU简单介绍 性能优异
  • 面向智能家居安全的异常行为识别与应急联动关键技术研究与系统实现(源码+论文+部署讲解等)
  • 软考【网络工程师】2023年5月上午题答案解析
  • dedecms织梦arclist标签noflag属性过滤多个参数
  • 2025年GPLT团体程序设计天梯赛L1-L2
  • RPCRT4!NdrPointerUnmarshall函数之ADVAPI32!LsarQueryInformationPolicy函数调用的一个例子
  • 【ESP32-IDF笔记】20-配置以太网网络(W5500)
  • 杂项知识点
  • 基于python代码的通过爬虫方式实现快手发布视频(2025年4月)
  • 模式识别的局限和确认偏误消除偏见
  • LeetCode 每日一题 2799. 统计完全子数组的数目
  • 项目笔记2:post请求是什么,还有什么请求
  • Uni-App 多端电子合同开源项目介绍
  • 单精度浮点运算/定点运算下 MATLAB (VS) VIVADO
  • Excalidraw工具分享
  • 速成GO访问sql,个人笔记
  • CodeMeter Runtime 安装失败排查与解决指南
  • 蓝牙调试助手APP波形图版
  • 软件工程效率优化:一个分层解耦与熵减驱动的系统框架
  • java配置
  • mysql知识总结 索引篇
  • Flutter Dart中的类 对象
  • 05-GPIO原理
  • 「零配置陷阱」:现代全栈工具链的复杂度管控实践
  • java多线程(7.0)
  • 发放优惠券
  • Java常用API详解
  • 通过VIN车辆识别代码查询_精准版API,获取车辆精准参数
  • 并发编程【深度解剖】