<!DOCTYPE HTML> <html> <head> <title>导航定位</title> <meta charset="utf-8"> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <script src="jquery-1.11.3.min.js"></script> </head> <style type="text/css"> * { margin:0px; padding:0px; font-family:‘微软雅黑‘; } div { height:400px; border:1px solid red; width:600px; } ul { overflow:hidden; position:fixed; top:300px; left:650px; } li { width:40px; height:40px; background:#3F883E; text-align:center; line-height:40px; color: rgb(0,255,0); ,font-size:18px; cursor:pointer; border-bottom:1px solid #fff; } li.active { width: 38px; height: 38px; margin-bottom: 1px; border: 1px solid #3F883E; background: #fff; color: rgb(255,0,0); } </style> <body> <div class="div1">段落1</div> <div class="div2">段落2</div> <div class="div3">段落3</div> <div class="div4">段落4</div> <div class="div5">段落5</div> <div class="div6">段落6</div> <div class="div7">段落7</div> <ul> <li class="li1 active">1</li> <li class="li2">2</li> <li class="li3">3</li> <li class="li4">4</li> <li class="li5">5</li> <li class="li6">6</li> <li class="li7">7</li> </ul> <script type="text/javascript"> // 匹配元素的左上角相对文档左上角的偏移 var arrOffsetTop = [ $(‘.div1‘).offset().top, $(‘.div2‘).offset().top, $(‘.div3‘).offset().top, $(‘.div4‘).offset().top, $(‘.div5‘).offset().top, $(‘.div6‘).offset().top, $(‘.div7‘).offset().top ]; var fTotalHgt = 0; for(var i=0; i<$(‘div‘).length; i++) { //返回匹配元素的外部高度,包含padding和border,不包含margin fTotalHgt += $(‘div‘).eq(i).outerHeight(); } //平均高度,用于调整滚动 var fAverageHgt = parseFloat(fTotalHgt / $(‘div‘).length); // 滚动事件(每次滚动都做一次循环判断) $(window).scroll(function() { for(var i=0; i<$(‘div‘).length; i++) { //页面滚动条的位置 if($(this).scrollTop() > arrOffsetTop[i] - fAverageHgt) { // 减去一个固定值,是定位准确点 $(‘ul li‘).eq(i).addClass(‘active‘).siblings().removeClass(‘active‘); } } }); /* 点击事件 */ $(‘ul li‘).click(function() { $(this).addClass(‘active‘).siblings().removeClass(‘active‘); //在500ms之内,将body的滚动条滚动到指定位置 $(‘body, html‘).animate({scrollTop: arrOffsetTop[$(this).index()]}, 500); }); </script> </body> </html>
时间: 2024-11-06 14:29:19