$(function(){ $("ul li a").click(function(){ var hr = $(this).attr("href"); var anh = $(hr).offset().top; $("html,body").stop().animate({scrollTop:anh},2000); }) })
ul{
position:fixed;
top:0;
background:#999999;
}
ul li{
float:left;
margin:10px;
padding:10px;}
<ul> <li><a href="#us">111111</a></li> <li><a href="#about">22222</a></li> <li><a href="#prouct">33333</a></li> <li>44444</li> <li>55555</li> <li>66666</li> </ul> <div style="clear:both;"></div> <div id="us" style="height:820px; background:#6699CC; width:100%;"></div> <div id="about" style="height:820px; background:#0066CC; width:100%;"></div> <div id="prouct" style="height:820px; background:#003366; width:100%;"></div>
同一個頁面中做錨鏈接,可以點擊元素,讓頁面跳到指定位置。
現在做的這個效果,不是突默認的瞬間跳到指定位置,而是滑動。這樣的用戶體驗會好些。
思路:
1.獲取到需要跳到頁面地方的元素,想對於頁面頂部的距離 $(hr).offset().top;
2.將這個值給html或body元素,讓其滾動條,執行一個animate動畫。這個動畫,是改變瀏覽器滾動條相對頂部的值。
注意:
1.$(this).attr("href");這返回期,正好可以做為JQuery的選擇器。
2..stop()防止不停點擊,會不停產生動畫列隊的bug.
參看網站:http://doubleleft.com/