上代码,好睡觉,IE有点兼容问题,IE只讨论>=8的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
.section{
width: 100%;
}
.section:nth-child(1){
background: #db7078;
}
.section:nth-child(2){
background: #ddd8ce;
}
.section:nth-child(3){
background: #0a9dc7;
}
.section:nth-child(4){
background: #1CBA9F;
}
.section:nth-child(5){
background: #E1CB82;
}
.nav{
position: fixed;
top: 0;
left: 0;
}
.nav a[rel="external"]{
display: inline-block;
width: 100px;
height: 50px;
background: #0a9dc7;
margin-right: 20px;
}
.wrapper{
margin-top: 100px;
}
.current{
color: red;
font-weight: 800;
}
</style>
</head>
<body onload="Apf.Common()">
<div class="container">
<div class="wrapper">
<div class="section" id="section1">section1</div>
<div style="width: 100%;height: 200px">随意添加</div>
<div class="section" id="section2">
section2
<div style="width: 100%;height: 200px;background: black;margin-bottom: 20px">随意添加</div>
<div style="width: 100%;height: 200px;background: black;margin-bottom: 20px">随意添加</div>
</div>
<div class="section" id="section3">section3
<div style="height: 400px">加的</div>
</div>
<div class="section" id="section4">section4
<div style="width: 100%;height: 200px;background: black;margin-bottom: 20px">随意添加</div></div>
<div class="section" id="section5" style="height: 400px;">section5</div>
</div>
<div class="nav">
<!--考虑到有些时候网站安全性,跳转锚点被占用,所以此方法支持可不需要href属性-->
<p rel="external nofollow" class="tab current">section1</p>
<p rel="external nofollow" class="tab">section2</p>
<p rel="external nofollow" class="tab">section3</p>
<p rel="external nofollow" class="tab">section4</p>
<p rel="external nofollow" class="tab">section5</p>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.js"></script>
<script src="Apf.js"></script>
<script type="application/javascript">
function Anchor(){
var _this = this;
var $navs = $('.nav .tab'), // 导航
$sections = $('.section'), // 模块
$window = $(window),
navLength = $navs.length - 1;
_this.toLocation.moveToPlace($navs,$window,$sections,navLength);
}
Anchor.prototype.toLocation = {
moveToPlace: function($navs,$window,$sections,navLength){
$navs.on('click', function(e) {
e.preventDefault();
console.log(this == e);
var tabIndex = $(this).index();
$('html, body').animate({
'scrollTop': $sections.eq(tabIndex).offset().top-100
}, 400);
});
$window.on('scroll', function() {
var scrollTop = $window.scrollTop(),
len = navLength;
for (; len > -1; len--) {
var that = $sections.eq(len);
if (scrollTop >= (that.offset().top-100)) {
$navs.removeClass('current').eq(len).addClass('current');
break;
}
}
});
}
}
var Anchor = new Anchor();
</script>
</body>
</html>