<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body {margin:0;padding:0;}
.nav {width:100%;height:50px;position:fixed;top:0;left:0;background-color:#333;text-align:center;line-height:50px;}
.nav a {margin:0 10px;color:#ddd;text-decoration:none;font-size:16px;}
.nav .cur {font-weight:bold;color:#f90;}
</style>
</head>
<body>
<div class="nav">
<a class="cur" href="#a1">恩恩恩</a>
<a href="#a2">嘿嘿嘿</a>
<a href="#a3">哈哈哈</a>
<a href="#a4">啊啊啊</a>
</div>
<div id="a1" class="section" style="height:800px;background:#f60;"></div>
<div id="a2" class="section" style="height:900px;background:#8cf;"></div>
<div id="a3" class="section" style="height:1200px;background:#FC9;"></div>
<div id="a4" class="section" style="height:800px;background:grey;"></div>
<script src="jquery-1.11.1.min.js"></script>
<script>
$(function() {
var act = $(".nav a");
var section = $(".section");
var timer = null;
act.on("click", function() {
var self = $(this);
var linkHref = self.attr("href").split("#")[1];
var target = $("#" + linkHref);
var topPos = target.offset().top - 50;
act.removeClass("cur");
self.addClass("cur");
$("html, body").animate({scrollTop: topPos}, "fast");
});
function scrollEvent() {
var posTop = $(window).scrollTop();
section.each(function() {
var self = $(this);
var elemTop = self.offset().top - 50;
var index = 0;
if (posTop >= elemTop) {
index = section.index(self);
act.removeClass("cur").eq(index).addClass("cur");
}
});
}
$(window).on("scroll", function() {
//scrollEvent();
clearTimeout(timer);
timer = setTimeout(scrollEvent, 100);
});
});
</script>
</body>
</html>
来源:https://www.cnblogs.com/huanlei/p/4184770.html