如何獲取滾動(dòng)高度:使用 window.scrolly 或 document.scrollingelement.scrolltop 屬性獲取當(dāng)前可見(jiàn)區(qū)域頂部到文檔頂部的像素?cái)?shù)。
如何在 JavaScript 中獲取滾動(dòng)高度
獲取滾動(dòng)高度的方法
在 JavaScript 中,獲取滾動(dòng)高度有兩種主要方法:
1. window.scrollY
window.scrollY 屬性表示文檔從頂部滾動(dòng)到當(dāng)前可視區(qū)域頂部的像素?cái)?shù)。
對(duì)于較舊的瀏覽器,可以使用 document.documentElement.scrollTop 代替。
2. document.scrollingElement.scrollTop
document.scrollingElement.scrollTop 屬性表示文檔從頂部滾動(dòng)到當(dāng)前可視區(qū)域頂部的像素?cái)?shù)。
它是 window.scrollY 的現(xiàn)代替代方案,適用于所有現(xiàn)代瀏覽器。
示例
以下代碼片段演示了如何使用 window.scrollY 獲取滾動(dòng)高度:
const scrollHeight = window.scrollY; console.log("當(dāng)前滾動(dòng)高度:" + scrollHeight);
登錄后復(fù)制
以下代碼片段演示了如何使用 document.scrollingElement.scrollTop 獲取滾動(dòng)高度:
const scrollHeight = document.scrollingElement.scrollTop; console.log("當(dāng)前滾動(dòng)高度:" + scrollHeight);
登錄后復(fù)制
注意:
這些方法返回的值以像素為單位。
滾動(dòng)高度可能因?yàn)g覽器、設(shè)備和文檔大小而異。