DIV CSS 佈局教程網

用 jQuery 依錨點 offset 值實現動畫滾動切換
編輯:關於JavaScript     

錨點大家都用過吧!但點擊後那種「瞬間硬跳」的切換體驗,是不是讓人覺得不夠順暢?本文分享一個小技巧:根據錨點的 offset 值,用 jQuery 做出平滑捲動的動畫切換效果。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>無標題文檔</title> <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> <style> *{ margin:0; padding:0;} .main{ width:1000px; margin:0 auto; position:relative; } .main img{ float:left;} .bg{ position:absolute; width:100%; z-index:-5;} .bg01{ height:885px;background:url(../images/b_01.jpg) no-repeat center;} .bg02{ height:938px;background:url(../images/b_04.jpg) no-repeat center; } .bg03{ height:946px;background:url(../images/b_02.jpg) no-repeat center; } .bg04{ height:946px;background:url(../images/b_03.jpg) no-repeat center; } .div_scoll{ position:fixed; width:50px; height:200px; right:100px; top:50%;} a{ display:block; background:#3F6; color:#000; width:50px; height:50px; } </style> </head> <body> <div class="wrapper"> <div class="main"> <div id="tab_01" class="tab"><img src="images/m_01.jpg" alt="" /></div> <div id="tab_02" class="tab"><img src="images/m_04.jpg" alt="" /></div> <div id="tab_03" class="tab"><img src="images/m_02.jpg" alt="" /></div> <div id="tab_04" class="tab"><img src="images/m_03.jpg" alt="" /></div> </div> <div class="bg"> <div class="bg01" id="bg01"></div> <div class="bg02" id="bg02"></div> <div class="bg03" id="bg03"></div> <div class="bg04" id="bg04"></div> </div> </div> <div class="div_scoll"> <a href="#bg01">圖1</a> <a href="#bg02">圖2</a> <a href="#bg03">圖3</a> <a href="#bg04">圖4</a> </div> <script> $(function(){ $(".div_scoll a").click(function(){ $("html,body").animate({ scrollTop:$($(this).attr("href")).offset().top + "px"},1000); }); }); </script> </body> </html>

整個效果的關鍵就在最後那段 JavaScript:當使用者點擊側邊的錨點連結時,先透過 $(this).attr("href") 取得連結指向的錨點(例如 #bg02),再用 $("...").offset().top 取得該區塊相對於頁面的頂部位置,最後用 jQuery 的 animate 方法在 1 秒(1000 毫秒)內平滑捲動到該位置。

相較於傳統錨點瞬間跳轉,這種「依 offset 值做 animate 捲動」的方式,讓頁面切換有了柔和的過渡動畫,用在單頁式網站的章節導覽、回到頂部等功能上,都能大幅提升使用者體驗。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved