2 回答

TA貢獻1820條經驗 獲得超10個贊
受上回答啟發確實跟css有關,
但是:
html {
height: 100%;
overflow: scroll;
}
這樣寫是獲取不到值的
html {
height: 100%;
overflow: visible;
}
這樣寫就可以獲取到值了,所以跟html的高度是否是100%并無關系

TA貢獻1788條經驗 獲得超4個贊
和你的頁面布局有關。
正常情況下滾動條是屬于 html 的,頁面撐開可以正常獲取document.documentElement.scrollTop。
在滾動條屬于 html 或 body 的情況下document.body.scrollTop || document.documentElement.scrollTop能正常拿到相應值。
如果都為0,那說明:
當前滾動條位置就是在頂部。
沒有產生滾動。
你當前的滾動條不再屬于 html 或者 body。
其它我沒想到的= =。
比如以下這種結構對應3:
<!DOCTYPE html>
<html>
<body>
<div class="wrapper">
<div class="main"></div>
</div>
</body>
</html>
<style>
html, body, .wrapper {
width: 100%;
height: 100%;
overflow: auto;
}
.main {
height: 10000px;
}
</style>
這樣.main撐開的滾動條其實是屬于.wrapper的。只有wrapper.scrollTop可以獲取相應的值。
document.body.scrollTop || document.documentElement.scrollTop自然始終為0。
添加回答
舉報