Javascript实现导航锚点滚动效果实例
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
<script src="jquery.1.8.3.html"></script>
<style>
.section{
height:200px;
width: 100%;
}
#section1{
background: red;
}
#section2{
background: blue;
}
#section3{
background: gold;
}
#section4{
background: green;
}
#section5{
background: cyan;
}
nav{ position: fixed; width: 100px; right: 10px; top: 20px;}
</style>
</head>
<body>
<p class="container">
<p class="wrapper">
<p class="section" id="section1">section1</p>
<p class="section" id="section2">section2</p>
<p class="section" id="section3">section3</p>
<p class="section" id="section4">section4</p>
<p class="section" id="section5">section5</p>
</p>
<nav>
<a href="#section1" rel="external nofollow" class="current">section1</a>
<a href="#section2" rel="external nofollow">section2</a>
<a href="#section3" rel="external nofollow">section3</a>
<a href="#section4" rel="external nofollow">section4</a>
<a href="#section5" rel="external nofollow">section5</a>
</nav>
</p>
</body>
<script>
//这个和下面代码可以选择一种
// var $navs = $('nav a'), // 导航
//$sections = $('.section'), // 模块
//$window = $(window),
//navLength = $navs.length - 1;
//
//$window.on('scroll', function() {
//var scrollTop = $window.scrollTop(),
// len = navLength;
//
//for (; len > -1; len--) {
// var that = $sections.eq(len);
// if (scrollTop >= that.offset().top) {
// $navs.removeClass('current').eq(len).addClass('current');
// break;
// }
//}
$navs.on('click', function(e) {
e.preventDefault();
$('html, body').animate({
'scrollTop': $($(this).attr('href')).offset().top
}, 400);
});
</script>
</html>