當頁面高度超過視窗,使用者捲動時,文件座標系統與視窗座標系統會產生位移。jQuery 提供 $(document).scrollTop() 與 $(document).scrollLeft() 兩個方法,回傳文件已向上/向左捲動的像素數,是定位浮動元素、固定導覽列、懶加載圖片的關鍵 API。
// 文件向上捲動了多少像素
var top = $(document).scrollTop();
// 文件向左捲動了多少像素
var left = $(document).scrollLeft();
$.fn.centerInViewport = function() {
this.css('position', 'absolute');
this.css('top', ($(window).height() - this.outerHeight()) / 2 + $(document).scrollTop() + 'px');
this.css('left', ($(window).width() - this.outerWidth()) / 2 + $(document).scrollLeft() + 'px');
return this;
};
// 使用範例
$('#popup').centerInViewport();
$(window).on('scroll resize', function() {
$('#popup').centerInViewport();
});
function showTooltip(el, text) {
var $tip = $('').text(text).appendTo('body');
var offset = $(el).offset();
var top = offset.top - $tip.outerHeight() - 10;
var left = offset.left + ($(el).outerWidth() - $tip.outerWidth()) / 2;
// 防止超出視窗上緣
var scrollTop = $(document).scrollTop();
if (top < scrollTop) top = scrollTop + 10;
$tip.css({ top: top, left: left });
}
原生 JS 替代方案(無相依)
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
常見坑點提醒
$(window).scrollTop() 與 $(document).scrollTop() 在標準模式下數值相同,但怪異模式下可能不同,建議統一用 $(document)。
- 行動裝置
scroll 事件可能不觸發(iOS momentum scrolling),需搭配 touchmove 或 IntersectionObserver。
- 固定定位 (
position: fixed) 元素不受捲動影響,勿混淆。
總結
掌握 scrollTop/scrollLeft 是前端定位技術的基石,配合 offset()、position()、outerWidth() 等尺寸 API,即可實作各類浮動、吸頂、懶加載、無限捲動等高階互動效果。
- 上一篇程序編程: JavaScript 判斷兩陣列元素型別與數量是否相似
- 下一篇程序編程: 7 個實用 jQuery 代碼片段:新窗口連結、等高欄位、圖片預載、禁用右鍵等