有沒有辦法在按下按鈕時立即捕捉到頁面頂部而無需滾動?我看到有幾種方法可以滾動到頂部,但它們總是有點平滑滾動。
uj5u.com熱心網友回復:
這是如何做到的:
// the button is stored in the variable topScroll
// the first parameter in scrollTo is x axis and second is y
topScroll.onclick = () => window.scrollTo(window.scrollX, 0);
//If you don't want to manipulate scrollX
topScroll.onclick = () => window.scrollTo(window.scrollX, 0);
告訴我這是否有效
uj5u.com熱心網友回復:
document.addEventListener("DOMContentLoaded", function(){
// We get the Container Element, to prepend some random Elements to increase the Length.
const containerEl = document.getElementById('container')
// Loop to insert 100 paragraph elements with random Number
for(let i = 0; i < 100; i ){
const newEl = document.createElement('p');
newEl.innerText = Math.floor(Math.random()*1000000);
containerEl.prepend(newEl);
}
// We create a Header Element for the Top page
const titleEl = document.createElement("h1");
titleEl.innerText = "U.S.S Enterprise";
containerEl.prepend(titleEl);
// We jump to the bottom of the Page
const containerHeight = containerEl.offsetHeight;
window.scrollTo(0, containerHeight);
// We add a EventListener for the Button at the bottom of the Page
document.getElementById('scrollTopBtn').addEventListener("click", function(){
// When clicked, we jump to the top of the page
// The User can set a default Behavior for scrolling in the Browser as Accessability
// Setting. If you dont override it, it defaults to auto and using this browser set
// Setting. Therefore we define the behavior as instant.
window.scrollTo({
top: 0,
left: 0,
behavior: 'instant'
});
});
})
<div id="container">
<button id="scrollTopBtn">Beam me up, Scotty!</button>
</div>
uj5u.com熱心網友回復:
當用戶單擊按鈕時使用此功能:
function scrollToTop(){
document.documentElement.scrollTop = 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/507647.html
標籤:javascript html css
上一篇:如何解決編碼挑戰的時間限制