【问题标题】:how to push webpage down to fit a top bar如何将网页向下推以适合顶部栏
【发布时间】:2026-01-25 12:45:01
【问题描述】:

有没有办法使用 javascript 测量 div 元素的高度?

这是我的情况: 我在我的网站上创建了一个顶部固定位置栏,所以即使我向上/向下滚动页面,该栏仍保持在顶部,但我的问题是栏覆盖了网页,我想要的是栏将网页向下推至高度条,所以它们看起来像堆叠,我设法通过固定高度来做到这一点,比如 50ox,我设置了 html 页面上边距,它们看起来不错,当条的高度发生变化时,例如在手机中查看相同的页面会出错,因为高度移动设备中 bar 的增加,但我设置的上边距仍然是 50,所以我需要一种方法来测量 ti 渲染时 bar 的实际高度并根据它调整页面。

【问题讨论】:

标签: javascript jquery html css responsive-design


【解决方案1】:

如果您将顶部栏固定在适当的位置,则不必担心其下方的内容实际上会显示在其下方,除非您也修改了它们的位置。如果是这种情况,那么您可以使用 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>

【讨论】:

    最近更新 更多