HTML:html
<html> <body> <div id="back-to-top" style="cursor:pointer; display:block;"> 上升按鈕 </div> </body> </html>
JS:this
$(function(){ //當滾動條的位置處於距頂部100像素如下時,跳轉連接出現,不然消失 $(function () { $(window).scroll(function(){ if ($(window).scrollTop()>100){ $("#back-to-top").fadeIn(1500); } else { $("#back-to-top").fadeOut(1500); } }); //當點擊跳轉連接後,回到頁面頂部位置 $("#back-to-top").click(function(){ $('body,html').animate({scrollTop:0},1000); return false; }); }); });
======spa
擴展升級:code
點擊菜單按鈕, 動態滾動到對應位置.htm
HTML:blog
<div id="header_nav"> <ul> <li> <a href="#home">首頁</a> </li> <li> <a href="#download">下載</a> </li> <li> <a href="#contact">聯繫</a> </li> </ul> </div>
JS:it
// -- initial -- $(document).ready(function() { $("#header_nav a").click(function(){ var selector=$(this).attr("href"); var top = $(selector).offset().top; var current_top = $('body').scrollTop(); var animate_time= Math.abs( current_top - top ) * 0.8; // 800px per second. $('body,html').animate({scrollTop:top},animate_time); return false; }); });