[英]Find minimum height of div with changing content so that page below doesn't jump around
[英]How to find height of a section of the page below a div?
假設我有以下HTML頁面:
<body>
<div id="top" style="height: 100px"></div>
</div>
如何找到div#top
以下頁面的高度並將其分配給JavaScript中的變量(允許使用jQuery)?
我的意思是:
<body>
.-------------------------------. ^
| <div id="top">...</div> | | 100 px
|-------------------------------| v
| ^ | ^
| | | |
| How do I find | | | rest of the page
| this height: | | | (nothing here, it's empty)
| | | |
| | | |
| | | |
| | | |
| v | v
'-------------------------------'
</body>
例如,如果瀏覽器窗口高度的可見部分是1000px,那么我正在尋找900px的答案。 如果窗口高度為777px,那么我正在尋找677px的答案。 等等。
您無法在CSS中動態找到高度,但可以使用calc()
計算剩余高度。
在這種情況下,可以使用height: calc(100% - 100px)
。
您還可以使用視口相對單位height: calc(100vh - 100px)
。
如果要動態查找元素下方的空間量,只需從元素底部的位置減去視口的高度即可。
純JavaScript :( 示例)
var element = document.querySelector('#target'),
remainingHeight = document.documentElement.clientHeight - element.getBoundingClientRect().bottom;
alert(remainingHeight); // Height below element
具有更高可讀性的等效版本:
var element = document.querySelector('#target'),
elementBottom = element.getBoundingClientRect().bottom,
viewportHeight = document.documentElement.clientHeight,
remainingHeight = viewportHeight - elementBottom;
alert(remainingHeight); // Height below element
jQuery替代品:( 示例)
var $element = $('#target'),
remainingHeight = $(window).height() - ($element.position().top + $element.outerHeight(true));
alert(remainingHeight); // Height below element
具有更高可讀性的等效版本:
var $element = $('#target'),
elementBottom = $element.position().top + $element.outerHeight(true),
viewportHeight = $(window).height(),
remainingHeight = viewportHeight - elementBottom;
alert(remainingHeight); // Height below element
只需考慮這兩種解決方案的盒式模型,然后進行相應調整。 上面的JavaScript方法沒有考慮元素的邊距; 而jQuery解決方案可以 。 您尚未明確說明您想要哪個。
我認為代碼是不言自明的。 這是一個小提琴 。 調整框架高度的大小以查看高度的變化。
var topElement = document.getElementById("top"); var topElementHeight = parseInt(getComputedStyle(topElement).height, 10); var windowHeight = window.innerHeight; var bodyMargin = parseInt(getComputedStyle(document.body).margin, 10); var availableHeight = windowHeight - topElementHeight - bodyMargin; topElement.innerText = availableHeight;
#top { height: 100px; background: red; }
<div id="top"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.