html - 在背景图片之后保持导航在顶部

标签 html css

我非常清楚如何通过在 CSS 中插入 position:fixed;top:0; 来使导航栏保持在顶部。但是,我想要的与这个不同。

我想要的是在导航栏之前插入一个新的 div(仅用于图像)。因此,当我打开网页时,我希望在向下滚动页面之前先查看图像。向下滚动图像后,我们可以看到那里有一个导航栏。而且当我在导航栏后继续向下滚动时,我希望导航栏停留在页面顶部。

我的意思的例子是here .

到目前为止,我所做的是在导航栏之前包含 .home。我做的比较乱。下面是代码:

.home {
min-height:400px; 
}

#header-center {
  margin: 0 auto;
}
#headerleft {
  float: left;
  margin: 20px;
}
#header,
#top {
  height: 80px;
  background-color: #E0E0E1;
  color: #FFF;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 9999;
}
#header p,
#top p {
  color: #FFF;
}
#header h1,
#top h1 {
  font-size: 20px;
  margin-top: 10px;
  letter-spacing: 0;
}
#header h1 a,
#top h1 a {
  font-size: 25px;
  color: #FFF;
  text-decoration: none;
}
#header h1 a:hover,
#top h1 a:hover {
  color: #FFF;
}
#headerleft h1 {
  font-family: Calibri sans-serif;
  font-size: 25px;
  letter-spacing: 1px;
}
#headerleft h1 a:hover {
  color: #CCC;
}
#nav {
  float: right;
}
#nav-icon img {
  display: none;
}
#nav ul li {
  float: left;
  list-style:none;
}
#nav ul li a {
  font-size: 20px;
  color: #FFF;
  margin: 0px;
  padding: 10px;
  text-decoration: none;
  float: left;
  font-family: 'alegreya_sansregular';
  cursor: pointer;
}
#nav ul li a:hover {
  border-bottom: 4px double #FFF;
}
<div class="home">
  <img src="assets/images/wallpaper.png" />
</div>

<div id="header">
  <div id="header-center">
    <div id="headerleft">
      <h1> <a href="#"> LOGO </a> </h1>
    </div>

    <div id="nav">
      <a href="" id="nav-icon">
        <img src="assets/images/navigation.png" alt="nav-menu">
      </a>
      <ul>
        <li> <a class="link-nav" data-scroll-nav="0"> HOME </a> 
        </li>
        <li> <a href="works"> WORKS </a> 
        </li>
        <li> <a data-scroll-nav="1"> ABOUT </a> 
        </li>
        <li> <a data-scroll-nav="2"> CONTACT </a> 
        </li>
      </ul>
    </div>
  </div>
</div>

你能告诉我我的代码有什么问题吗?谢谢。

最佳答案

可以先在css中设置header为position:relative。然后你会添加 jquery 或 javascript 说 - 当你滚动超过 400px 垂直(y)位置时,改变 position:relative 到 position:fixed。这通常是它的工作原理。

要回答您的评论,您可以添加一个 css 样式:

.fixedPosition {
    position:fixed !important;
    top: 0;
    left: 0;
} 

然后添加 jQuery(如果需要,不要忘记放置库和文档就绪函数):

  $(window).scroll(function () {
    var y = $(window).scrollTop(); 

    if (y > 400) {       
       $('#header').addClass('fixedPosition');
    } else { 
       $('#header').removeClass('fixedPosition'); 
    } 
});

这是一个 FIDDLE

关于html - 在背景图片之后保持导航在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29003347/

相关文章:

javascript - setinterval 不一次性改变样式

javascript - React - 如何将图像复制到剪贴板?

javascript - 如何定位特定 <DIV> 的 jQuery 对话框 "Center and Middle"

jquery - 更改展开和折叠的图标

css - 在 Shiny 演练中更改 sliderInput 的颜色

css - 只能单击 svg 图像的边缘吗?

html - 如何使 html 忽略作为文本一部分的代码?

html - Zindex 无法正常工作

html - 悬停时背景图像和颜色随持续时间变化

css - 窗口宽背景与宽度受限的 div 相结合