function scrollToTop() {
window.scrollTo(0, 0);
}
function smoothScrollToTop() {
const currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothScrollToTop);
window.scrollTo(0, currentScroll - (currentScroll / 8));
}
}
function scrollToElementTop(element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function animateScrollToTop(duration) {
const start = document.documentElement.scrollTop || document.body.scrollTop;
const target = 0;
const distance = target - start;
const startTime = performance.now();
function step() {
const currentTime = performance.now();
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easing = function(t) { return t * (2 - t); }; // 緩動函數,例如使用二次方函數
const position = start + distance * easing(progress);
window.scrollTo(0, position);
if (progress < 1) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
<button id="scrollToTopBtn">回到頂部</button>
document.getElementById('scrollToTopBtn').addEventListener('click', scrollToTop);
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
以上是五種常見的回到頁面頂部的實現方法,從最基本的滾動到頂部到增強版帶有平滑滾動效果和按鈕點擊事件的寫法。可以根據具體需求選擇相應的方法來實現回到頁面頂部的功能。