<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <style type="text/css"> *{ padding:0; margin: 0 } .div1{ margin-top: 40px; background-color: red; } .div2{ background-color: blue; } .div3{ background-color: black; } .box{ width: 100%; height: 900px; } .nav{ position: fixed; width: 100%; top: 0; line-height: 40px; overflow:hidden; background-color: #fff; opacity: 0.8;
font-weight:800 } .nav li{ float: left; width: 120px; text-align: center; cursor: pointer; } .nav li.active{ color: red } </style> </head> <body> <ul class="nav"> <li class="active">red</li> <li>blue</li> <li>black</li> </ul> <div class="box div1"></div> <div class="box div2"></div> <div class="box div3"></div> <script> $(window).scroll(function(){ var top = $(this).scrollTop(); var height = $(this).height(); $('.box').each(function(i){ if ($(this).offset().top-40<= top) { $('.nav li').removeClass('active').eq(i).addClass('active'); } else return; }) }) $('.nav li').click(function(){ $('html').animate({ scrollTop: ($('.box').eq($(this).index()).offset().top-40) }, 300); }) </script> </body> </html>