jquery 跳转到当前页面指定位置

时间:2024-01-01 21:12:15
 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{padding:0;margin:0;}
.top{ width:100%; height:100px; text-align: center; line-height: 100px;}
.nav{ width:100%; height:100px;}
.nav ul{width:100%; list-style: none;}
.nav ul li { float:left; line-height:100px;
text-align: center; width:25%; background:#0095cd;}
.fixed {position:fixed; top:0px;}
.cont1,.cont2,.cont3,.cont4{width:100%;height:400px; color:#fff;}
.cont1 {background:#00678e; text-align:center; line-height: 400px;}
.cont2 {background:#0F3A56; text-align:center; line-height: 400px;}
.cont3 {background:#33bbee; text-align:center; line-height: 400px;}
.cont4 {background:#7ca1f8; text-align:center; line-height: 400px;}
.footer { background:#68767b; text-align:center;line-height:200px;}
</style>
<script src="style/js/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$(window).scroll(function(){
if ($(window).scrollTop() >= 100) {
$('.nav').addClass('fixed');
} else {
$('.nav').removeClass('fixed');
}
})
var _li = $('.nav').find('li');
_li.each(function(){
var index = $(this).index();
$(this).find('a').click(function(){
var len = index-1;
var numTop = getHeight(len);
$('html,body').animate({scrollTop: numTop + "px"},300);
})
})
})
function getHeight(index) {
var heightall = 0;
for(i=0;i<=index;i++){
heightall += 400;
}
return heightall;
}
</script>
</head>
<body>
<div class="top">这是顶部,高度为100px</div>
<div class="nav">
<ul>
<li><a>first</a></li>
<li><a>scond</a></li>
<li><a>third</a></li>
<li><a>four</a></li>
</ul>
</div>
<div class="cont1">this is content1</div>
<div class="cont2">this is content2</div>
<div class="cont3">this is content3</div>
<div class="cont4">this is content4</div>
<div class="footer">this is footer</div>
</body>
</html>