DIV CSS 佈局教程網

用 jQuery animate() 搭配 scrollTop 做平滑捲動定位
編輯:JavaScript綜合知識     

animate() 是 jQuery 的特效方法,能讓 CSS 屬性從目前狀態漸變到目標狀態,从而产生动画。需要注意的是,它只能處理數值型屬性,例如 margin:30px 可以,background-color:red 這類字串值則不行。

最簡單的例子

$('#shang').click(function () {
  $('html,body').animate({ scrollTop: '0px' }, 800);
});

點擊後捲軸會在 800 毫秒內移動到 0 的位置,也就是回到頁首。之所以要同時選 html 與 body,是為了相容不同瀏覽器對捲動容器的認定差異。

三個實用的按鈕

jQuery(document).ready(function ($) {
  $('#shang').click(function () {
    $('html,body').animate({ scrollTop: '0px' }, 800);
  });
  $('#comt').click(function () {
    $('html,body').animate({ scrollTop: $('#comments').offset().top }, 800);
  });
  $('#xia').click(function () {
    $('html,body').animate({ scrollTop: $('#footer').offset().top }, 800);
  });
});

三顆按鈕分別對應回到頂端、捲到 comments 區塊、捲到頁尾。offset().top 回傳元素頂部距文件頂端的距離,正好可以直接當作 scrollTop 的目標值。

兩個實務調整

第一,若頁首有固定高度的 header,捲到該區塊時標題會被遮住,目標值要再減去 header 的高度:

var top = $('#comments').offset().top - $('header').outerHeight();
$('html,body').animate({ scrollTop: top }, 800);

第二,animate 的 easing 預設是 swing(先快後慢),可改為 linear 或其他效果; duration 也可寫成 'slow'、'fast' 這類關鍵字。

若不想依賴 jQuery,現代做法是用 scrollIntoView({ behavior: 'smooth' }) 或 element.scrollTo({ top: 0, behavior: 'smooth' }),一行就能達到同樣效果,並會自動尊重系統的「減少動態效果」偏好設定。

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