我正在尝试让我的导航栏像在 forbes.com 上一样停留在页面顶部
我知道我能做到
nav
{
position: fixed;
top: 0;
}
但是导航栏不在页面顶部,它位于徽标之后…但是当您向下滚动时,我希望导航栏保持在屏幕顶部..
原文由 Adam Scot 发布,翻译遵循 CC BY-SA 4.0 许可协议
我正在尝试让我的导航栏像在 forbes.com 上一样停留在页面顶部
我知道我能做到
nav
{
position: fixed;
top: 0;
}
但是导航栏不在页面顶部,它位于徽标之后…但是当您向下滚动时,我希望导航栏保持在屏幕顶部..
原文由 Adam Scot 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可以像这样在 JQuery 中尝试它:
HTML:
<div id="wrapper">
<header>
<h1>Floater Navigation</h1>
</header>
<nav>
<p>Navigation Content</p>
</nav>
<div id="content">
<p>Lorem Ipsum.</p>
</div>
</div>
CSS:
#wrapper {
width:940px;
margin: 0 auto;
}
header {
text-align:center;
padding:70px 0;
}
nav {
background: #000000;
height: 60px;
width: 960px;
margin-left: -10px;
line-height:50px;
position: relative;
}
#content {
background: #fff;
height: 1500px; /* presetting the height */
box-shadow: 0 0 5px rgba(0,0,0,0.3);
}
.fixed {
position:fixed;
}
查询:
$(document).ready(function() {
// Calculate the height of <header>
// Use outerHeight() instead of height() if have padding
var aboveHeight = $('header').outerHeight();
// when scroll
$(window).scroll(function(){
// if scrolled down more than the header’s height
if ($(window).scrollTop() > aboveHeight){
// if yes, add “fixed” class to the <nav>
// add padding top to the #content
// (value is same as the height of the nav)
$('nav').addClass('fixed').css('top','0').next().css('padding-top','60px');
} else {
// when scroll up or less than aboveHeight,
// remove the “fixed” class, and the padding-top
$('nav').removeClass('fixed').next().css('padding-top','0');
}
});
});
来源: http ://www.jay-han.com/2011/11/10/simple-smart-sticky-navigation-bar-with-jquery/
原文由 mrtriangle 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答839 阅读✓ 已解决
4 回答913 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
2 回答811 阅读✓ 已解决
2 回答1k 阅读✓ 已解决
2 回答2.5k 阅读
解决方案很简单,在添加 px 的同时保留你的 css