【问题标题】:HTML & JavaScript - Responsive navbar not pushing content downHTML & JavaScript - 响应式导航栏不向下推送内容
【发布时间】:2021-03-05 09:41:34
【问题描述】:

我有一个 JavaScript 函数,当页面宽度小于 500 像素时,它会触发菜单按钮以打开响应式导航栏。但是当导航栏被触发打开时,导航栏会覆盖页面下方的内容。

有没有一种方法可以强制 div ID="content" (如下所示的代码)中的内容在打开时按导航栏的高度向下推,并在导航栏关闭时向上推回正常位置?

menuButton.addEventListener('click', ev => {
  topNav.classList.toggle('open');
});
@media screen and (min-width: 500px) {
  #menuButton {
    display: none;
  }
  nav {
    display: flex;
    flex-direction: row;
    transform: none;
    opacity: 1;
    height: auto;
    position: static;
  }
}
<div id="menuButton">&#8801;</div>
<nav id="topNav">
  <a href="index.html">Home</a>
  <a href="team.html">The Team</a>
  <a href="fixtures.html">Fixtures & Results</a>
  <a href="gallery.html">Gallery</a>
</nav>
<div id="content">
  <h1>Hello World</h1>
</div>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    是的,您可以使用纯 js 或 js 和 css 的组合来实现。下面是一个纯js的例子:

    // select your content layer
    const content = document.getElementById('content');
    
    menuButton.addEventListener('click', ev => {
      topNav.classList.toggle('open');
      // if menu is open
      if (topNav.classList.contains('open')) {
          // get the dimensions of the topNav
          const bbox = topNav.getBoundingClientRect();
          const height = bbox.height;
          const top = bbox.top;
          // calculate the new position of the content
          const positionTop = height+top;
          // update the style of the content layer to reflect the change
          contentLayer.style.position = 'absolute';
          contentLayer.style.top = positionTop;
      }
      else {
          contentLayer.style.position = 'relative';
          contentLayer.style.top = 0;
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多