【发布时间】:2016-08-16 16:13:51
【问题描述】:
我正在创建一个带有固定导航栏的单页网站。当我加载页面并单击一个链接时,它可以工作并向下移动到正确的链接。但是,当我单击另一个链接时,它会向上滚动到标题,之后任何链接都会滚动到页面的随机部分。
如何创建导航使其滚动到页面上的指定链接?
我正在使用 jquery 来修复标题和平滑滚动。
HTML
<div id="container">
<header>
<div id="logo"><img src="img/logo.png"></div>
<nav class="fixed-nav">
<ul>
<li><a href="#about">About Me</a></li>
<li><a href="#portfolio">Portfolio</a></li>
<li><a href="#audio">Audio</a></li>
<li><a href="#contMe">Contact Me</a></li>
</ul>
</nav>
</header>
<div id="main">
<section id="slider">
<p>Slider here</p>
</section>
<section id="aboutMe">
<a id="about" class="smooth"></a>
<h1>About Me</h1>
<p>about page here</p>
</section>
<section id="portfolio">
<a id="portfolio" class="smooth"></a>
<h1>Portfolio</h1>
<p>portfolio page here</p>
</section>
<section id="Audio">
<a id="Aud" class="smooth"></a>
<h1>Munro Audio</h1>
<p>Munro Audio page here</p>
</section>
<section id="contactMe">
<a id="contMe" class="smooth"></a>
<h1>Contact Me</h1>
<p>Contact Me page here</p>
</section>
</div>
</div>
平滑滚动和固定标题 Jquery
<!-- smooth scroll -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
//Fixed Header
var headerHeight = $('header').height();
$(window).scroll(function() {
if( $(this).scrollTop() > headerHeight) {
$('nav').addClass('fixed-nav');
} else {
$('nav').removeClass('fixed-nav');
}
});
</script>
CSS
body{
position: relative;
width:52.5%; /* 1000 px */
margin-left:auto;
margin-right:auto;
border: 1px solid black;
background-color: white;
}
#aboutMe, #portfolio, #munroAudio, #contactMe, #slider{
top:60px;
height:1000px;
position:relative;
}
#logo img {
max-width: 100%;
height: auto !important;
}
header, header img, header nav{
display:block;
margin-left:auto;
margin-right:auto;
}
header{
height:110px;
}
nav {
position:relative;
top:50px;
width: 100%;
background: #D24D57;
color: #fff;
height:60px;
}
ul {
list-style: none;
margin: 0;
}
ul li {
display: inline-block;
padding: 20px;
}
.fixed-nav {
position: fixed;
width: 52.5%;
top: 0;
z-index: 20;
}
.fixed-nav ul li {
display: inline-block;
padding: 20px;
}
.fixed-nav ul li:hover {
background: #E08283;
}
ul li {
display: inline-block;
padding: 20px;
}
ul li:hover {
background: #E08283;
}
【问题讨论】:
-
我注意到的第一件事是你有两个 id 为
portfolio的元素,但不确定是否是问题所在...... -
感谢现场。我更改了 ID,但它的行为仍然相同。
标签: jquery html css responsive-design nav