DIV CSS 佈局教程網

依錨點 offset 做平滑捲動:jQuery 動畫換頁小技巧
編輯:JavaScript綜合知識     

長頁面常會在側邊放一組快速跳轉連結,點下去希望畫面平滑捲到目標區塊,而不是瞬間跳過去。做法是取出目標元素的 offset().top,再用 animate 動畫把捲動位置移過去。

完整範例

<!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>

核心只有一行

整個效果關鍵在這句:

$("html,body").animate({ scrollTop: $($(this).attr("href")).offset().top + "px" }, 1000);

拆解來看:$(this).attr("href") 拿到 #bg02 這樣的錨點字串,$(...) 把它變成 jQuery 物件,.offset().top 取得該元素距離文件頂端的距離,最後 animate 用 1000 毫秒把 html 與 body 的 scrollTop 動畫式推到那個位置。

同時選 html,body 而不是只選其中一個,是為了相容不同瀏覽器——有些用 documentElement 捲動,有些用 body。

可以再加強的地方

如果目標區塊上方有固定高度的頁首,單純捲到 offset().top 會被頁首遮住,這時要再減去頁首高度:.offset().top - $('header').height()。

另外,純 CSS 其實也能做到平滑捲動,只要在樣式表加上 html { scroll-behavior: smooth; } 即可,不必載入 jQuery;只是它無法自訂速度與 easing 曲線,需要精細控制時還是得用 JS。

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