如何推送网页以适应顶部栏

时间:2017-01-03 20:42:34

标签: javascript jquery html css responsive-design

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

这是我的情况: 我在我的网站上创建了一个顶部固定位置栏,所以即使我向上/向下滚动页面,栏也保持在最顶层,但我的问题是栏覆盖网页,我想要的是将网页向下推到高度吧,所以他们看起来像堆叠,我设法按固定的高度,50ox,我设置HTML页面上边距,他们看起来没问题,当栏的高度改变,例如在手机中看同一页面出错是因为高度移动中的条形增加但我设置的上边距仍然是50,所以我需要一种方法来测量ti渲染时的实际条形高度,并根据它调整页面。

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;