javascript - 如何将 DIV 定位在具有动态大小的固定 DIV 下方

标签 javascript html css

我有一个类似导航栏的东西,它固定在侧面的顶部。现在我想在它下面有一个 content-DIV 。问题是,导航栏没有固定的高度。

我怎样才能做到这一点?

HTML:

<div id="nav">
this is my navigation bar
</div>
<div id="content">
HERE <br>
IS <br>
MUCH <br>
CONTENT
</div>

CSS:

#nav {
  position: fixed;
  background: lightblue;
}

JSFIDDLE:enter link description here

最佳答案

纯 Javascript 解决方案

使用 javascript,您可以获得 <div id="nav"> 的高度和位置并用它们来计算你的 <div id="content"> 的位置:

var navDivElement = document.getElementById("nav");
var contentDivElement = document.getElementById("content");

contentDivElement.style.top = navDivElement.clientHeight + navDivElement.getBoundingClientRect().top + 'px';

压力

如何获取元素的位置:

var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);

来源:https://stackoverflow.com/a/11396681/4032282

如何获取元素的尺寸:

var e = document.getElementById('id')
console.log(e.clientHeight, e.offsetHeight, e.scrollHeight);
  • clientHeight包括高度和垂直填充。
  • offsetHeight包括高度、垂直填充和垂直边框。
  • scrollHeight包括所包含文档的高度(在滚动的情况下会大于高度)、垂直填充和垂直边框。

来源:https://stackoverflow.com/a/526352/4032282

CSS Sticky 解决方案

更改 position: fixed;导航的 position: sticky;并添加 top: 0; .

那样<div id="content">会放在导航下面,但是导航会留在他容器的顶部。

<html>
  <head>
    <style>
    #nav {
      position: sticky;
      top: 0;
    }

    /* Allow you to play with the browser height to make the vertical scroll appears and use it to see that the nav will stay on top */
    #content {
      height: 500px;
      background-color: #ff0000;
    }
    </style>
  </head>
  <body>
    <div id="nav">NAV</div>
    <div id="content">CONTENT</div>
  </body>
</html>

关于javascript - 如何将 DIV 定位在具有动态大小的固定 DIV 下方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898558/

相关文章:

javascript - 将对象转换为数组 typescript

javascript - 响应式导航栏不会显示

html - 如何设置我的 HTML 表格布局

java - 将 java 列表传递给 html 模板

html - 更改媒体屏幕使 div 覆盖

javascript - 每个()函数上的jquery load()一起工作

使用 Rhino 将 Javascript 转换为 Java

html - float div 未在顶部对齐

html - 仅CSS的砌体布局

javascript - 未设置背景颜色