本文介紹如何在頁面加載時讓滾動條自動滾動到最底部,分別提供jQuery與原生JavaScript兩種實現方式。
代碼如下:
$(function(){
var h = $(document).height()-$(window).height();
$(document).scrollTop(h);
});
其原理是先用文檔總高度減去視窗高度,得到最大可滾動距離,再把滾動條定位到該位置。
代碼如下:
window.onload = function(){
var h = document.documentElement.scrollHeight || document.body.scrollHeight;
window.scrollTo(h,h);
}
這裡通過 scrollHeight 取得文檔的實際高度(兼容不同瀏覽器),再調用 window.scrollTo 滾動到底部。
以上兩種方法都能實現頁面加載時滾動條自動滾動到底部的效果,夥伴們可以根據自己的實際需求自由選擇。