$(function() {
$("a").click(function() {
if (this.hash) {
var hash = this.hash.substr(1);
var $scrollToElement = $("div[name=" + hash + "]");
var headerHeight = $('header').height();
var scrollToPosition = $scrollToElement.offset().top - headerHeight;
$("html, body").animate({
scrollTop: scrollToPosition
}, 1000, "swing");
$('.menuItem').removeClass('selected');
$(this).children('.menuItem').addClass('selected');
return false;
}
});
});
* {
padding: 0;
margin: 0 auto;
text-decoration: none;
}
body {
background: rgb(223, 227, 238);
text-align: center;
}
header {
min-width: 100%;
background: rgb(50, 50, 50);
height: 80px;
position: fixed;
z-index: 10;
}
#header_container {
max-width: 1024px;
height: 100%;
}
#header_container div {
float: left;
display: inline-block;
width: 25%;
}
#logo {
width: 50%;
height: auto;
}
.menuItem {
padding-top: 29px;
height: calc(100% - 29px);
border: 0;
text-align: center;
font-family: Signika;
font-size: 25px;
color: rgb(203, 207, 218);
}
.menuItem:hover {
border-bottom: 4px solid rgb(59, 89, 202);
height: calc(100% - 33px);
color: rgb(160, 170, 218);
}
.selected {
border-bottom: 4px solid rgb(59, 89, 202);
height: calc(100% - 33px);
color: rgb(160, 170, 218);
}
.menuLogo {
padding-top: 14.5px;
height: calc(100% - 14.5px);
border: 0;
text-align: center;
}
#mobile_menu_button {
display: none;
}
#body_container {
padding-top: 80px;
}
#banner_container {
position: fixed;
left: 0;
right: 0;
}
#banner {
width: 1024px;
height: auto;
}
#content_container {
background: rgb(235, 235, 240);
max-width: 1024px;
height: 100%;
position: relative;
top: 300px;
box-shadow: 0px 5px 10px rgb(235, 235, 240);
-webkit-box-shadow: 0px 5px 10px rgb(235, 235, 240);
}
#over_content {
width: 100%;
height: 1000px;
}
#contact_content {
background-color: rgb(200, 200, 200);
height: 1000px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<div id="header_container">
<div class="menuLogo">
<img id="logo" />
</div>
<a href="#home">
<div id="homeButton" class="menuItem selected">Home</div>
</a>
<a href="#over">
<div id="overButton" class="menuItem">Over</div>
</a>
<a href="#contact">
<div id="contactButton" class="menuItem">Contact</div>
</a>
<div id="mobile_menu_button"></div>
</div>
</header>
<div name="home" id="body_container">
<div id="banner_container">
<img id="banner" />
</div>
<div id="content_container">
<div name="over" id="over_content">Over menu's content</div>
<div name="contact" id="contact_content">Contact menu's content</div>
</div>
</div>
position().top
可能由于您的固定位置元素而没有返回正确的值。我会找出原因并发布一个答案(或者如果您愿意,我现在可以发布一个答案并稍后更新该部分)。 - Harry