【发布时间】:2016-12-29 23:07:16
【问题描述】:
我在自定义页面上的导航位于标题照片下方。当页面滚动时,我希望导航保持在顶部。但是,我无法让它保持在固定位置。我觉得我什么都试过了。想知道我的代码中的某些内容是否与脚本冲突以使其无法运行。
<div id="header">
<img src="images/header-1.jpg" style="max-width:100%; height:auto;"/>
</div>
<div id="headerTitle">
<h2>header</h2>
<h3><em>subhead</em></h3>
</div>
<nav id="navbar">
<div id="enter">
<div class="numberCircle"><span>5</span></div>
<div class="pg-nav">
<ul class="nav-links">
<li><a href="#a">A</a></li>
<li><a href="#b">B</a></li>
<li><a href="#c">C</a></li>
<li><a href="#d">D</a></li>
</ul>
</div>
</div>
</nav>
<style>
#navbar {
letter-spacing: 1px;
margin: 20px 0 20px 0;
width: 100%;
}
.fixedtop {
position: fixed;
z-index: 100;
width: 100%;
top: 0;
}
#enter {
background-attachment: scroll;
background-clip: border-box;
background-color: #696969;
background-image: none;
background-origin: padding-box;
background-position: 0 0;
background-repeat: repeat;
background-size: auto auto;
height: 30px;
line-height: 10px;
padding: 10px;
text-align: center;
border-bottom: #97233f solid 2px;
/* width: 100%; */
/* z-index: 9999; */
}
.pg-nav {
width: 100%;
margin: 0 auto;
text-align: left;
}
.pg-nav ul {
list-style-type: none;
margin: 0 0 0 10px;
padding: 0;
overflow: hidden;
position: relative;
display: inline-block;
}
.pg-nav li {
float: left;
padding: 12px;
font-weight: 900;
}
.pg-nav li a {
display: block;
font-family: "Lato",sans-serif;
color: #fff;
font-size: 11px;
font-weight: 900;
text-decoration: none;
text-transform: uppercase;
}
@media (max-width: 500px) {
.pg-nav li {width:100%; padding:5px;}
}
.pg-nav li a:hover {
color: #97233f;
}
.numberCircle {
border-radius: 50%;
width: 28px;
font-size: 21px;
border: 2px solid #fff;
float: left;
}
.numberCircle span {
text-align: center;
line-height: 28px;
display: block;
color: #fff;
}
</style>
<script>
$(function() {
var distance = $('#navbar').offset().top,
$window = $(window);
$window.scroll(function() {
$('#navbar').toggleClass('fixedtop', $window.scrollTop() >= distance)
});
});
</script>
【问题讨论】:
-
你有 jquery 吗?
-
你需要将
margin-top: 0 !important;添加到类.fixedtop样式定义中 -
是 jquery-3.1.1.min.js 和 jquery-3.1.1.js
-
为什么不将
navbar组件放在html 的顶部?或者您出于某种原因需要它位于标题下方?我也不明白你为什么要尝试使用 javascript,这肯定只是一个 css 问题。如果我错了,请纠正我。 -
这会让事情变得更容易,因为我可以使用 position:fixed;对于导航栏。我想尝试一种设计,其标题和顶部的照片类似于此页面:www.uconnhuskies.com/sports/w-baskbl/2016champs/index.html。据我所知,JavaScript 允许标题从标题下方移动到顶部。除非在我不知道的 CSS 中有更简单的方法来做到这一点?
标签: javascript jquery html css nav