當我在谷歌瀏覽器中重繪 頁面時,無論是移動設備還是電腦,滾動條都不會從頂部開始,這會導致我的頁面上出現視覺錯誤,它應該從頂部開始,因為我曾經overflow: hidden隱藏滾動條并且只使用滾動效果修改部分的位置。
所以,我想知道是否有辦法在 javascript 或 html 中操縱滾動條的位置,使其始終從頂部開始。這只發生在 Chrome 中
uj5u.com熱心網友回復:
只需設定document.scrollTop = 0頁面加載,這應該可以解決問題。
uj5u.com熱心網友回復:
聽起來你在尋找Element.scrollTop
const scroller = document.querySelector("#scroller");
const output = document.querySelector("#output");
const button = document.querySelector("#button");
button.addEventListener("click", () => scroller.scrollTop = 0);
scroller.addEventListener("scroll", (event) => {
output.textContent = `scrollTop: ${scroller.scrollTop}`;
});
#scroller {
overflow: scroll;
height: 150px;
width: 150px;
border: 5px dashed orange;
}
#output {
padding: 1rem 0;
}
<button id="button">Scroll to top</button>
<div id="container">
<div id="scroller">
<p>
Far out in the uncharted backwaters of the unfashionable end of the
western spiral arm of the Galaxy lies a small unregarded yellow sun.
Orbiting this at a distance of roughly ninety-two million miles is an
utterly insignificant little blue green planet whose ape-descended life
forms are so amazingly primitive that they still think digital watches are
a pretty neat idea.
</p>
</div>
</div>
<div id="output">scrollTop: 0</div>
uj5u.com熱心網友回復:
我通過添加執行功能的延遲解決了這個問題,我在 2016 年的這篇文章中找到了同樣經歷的人的解決方案
我添加了這個腳本:
let delay_ms = 15
document.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
window.scrollTo(0, 0);
console.log(scrollY);
}, delay_ms);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/517900.html
