是否有方法使用javascript测量div元素的高度?
这里是我的情况:我在我的网站上创建了一个固定位置栏,所以即使我向上/向下滚动页面,这个栏也会保持在顶部,但我的问题是在网页上放置条形图,我想要的是将网页向下推到栏的高度,这样它们看起来就像堆叠了的,我设法按固定的高度,比如50ox,设置了html页面的上边距,当条形图的高度发生变化时,它们看起来还可以,例如,当移动栏的高度发生变化时,因为移动栏的高度增加了,但是我设置的最高边距仍然是50,因此,我需要一种方法来测量实际高度的酒吧,当ti被渲染和调整页面根据它。
发布于 2017-01-03 20:49:26
如果您固定顶部栏的位置,您不应该担心下面的内容实际上显示在它下面,除非您已经修改了他们的位置。如果是这样的话,那么您可以使用window.getComputedStyle()计算元素的高度,并且可以使用该值来设置边距。
var wrapper = document.getElementById("wrapper");
var banner = document.getElementById("banner");
var content = document.getElementById("content");
var bannerHeight = window.getComputedStyle(banner).height;
console.log("Height of the banner is: " + bannerHeight);
content.style.marginTop = bannerHeight;
#wrapper { background: #e0e0e0; }
#banner { background: #ff0; position:fixed; top:0; width:100%; z-index:99; }
#content { background: #66f; position:relative; }
<div id="wrapper">
<div id="banner">
<h1>This is the page banner</h1>
</div>
<div id="content">
<h1>This is FIRST LINE of the main content area of the document.</h1>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
<p>This is the main content area of the document.</p>
</div>
</div>
https://stackoverflow.com/questions/41452011
复制相似问题