前端让一个div的高度为屏幕的高度减去其他所有元素的高度(包括它们的margin和padding),并自适应。
前端让一个div的高度为屏幕的高度减去其他所有元素的高度(包括它们的margin和padding),并自适应。
项目需求是让.adaptive-height的高度在不同的移动端中高度自适应。
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; /* 如果内容超出,添加滚动条 */
}