原理是:
1,先each循环,获取到每个元素距离文档顶部的距离
2,然后用window的scroll事件获取元素中滚动条的垂直偏移
3,然后把俩者进行比较
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js" ></script> </head> <body> <style type="text/css"> *{margin: 0;} .main div{ 100%; height: 800px; color: #fff; background: #007FFF; } .main div:nth-child(2n){ height: 1000px; background: #00DD1C; } .right{ position: fixed; right: 20px; bottom: 100px; } .right a{ display: block; margin: 5px; 20px; height: 20px; border-radius: 50%; background: #000; } .right a.active{ background: #2A6496; } </style> <div class="main"> <div class="one">111</div> <div class="one">222</div> <div class="one">333</div> <div class="one">444</div> <div class="one">555</div> </div> <div class="right"> <a class="active" href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> <a href="javascript:;"></a> </div> <script> $(function(){ $(".main div").each(function(i,index){ var that=$(this); //获取每个元素的距离文档顶部的高度 var windowTop = $(".main div").eq(i).offset().top -100 $(window).scroll(function(){ //console.log($(this).scrollTop(),windowTop) //用当前滚动文档的高度和获取元素文档的高度比较 if($(this).scrollTop() >= windowTop ){ $(".right a").eq(i).addClass('active').siblings().removeClass('active'); } }) }) }) </script> </body> </html>