Five ways to achieve scrolling back to the top of a webpage using JavaScript (from basic implementation to enhancement)
- You can achieve this using the window.scrollTo or document.documentElement.scrollTop method.
function scrollToTop() {
window.scrollTo(0, 0);
}
- Implement smooth scrolling effect by combining the window.scrollTo method with requestAnimationFrame.
function smoothScrollToTop() {
const currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothScrollToTop);
window.scrollTo(0, currentScroll - (currentScroll / 8));
}
}
- Utilize the scrollIntoView method to scroll to the top of a specified element.
function scrollToElementTop(element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
- Achieve smooth scrolling effect with the animate method.
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);
}
- Enhanced version: Add a button element and bind a click event.
<button id="scrollToTopBtn">回到顶部</button>
document.getElementById('scrollToTopBtn').addEventListener('click', scrollToTop);
function scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
Here are five common ways to implement a back to top button, ranging from the basic scroll to top to an enhanced version with smooth scrolling effects and button click event. You can choose the appropriate method based on your specific needs to achieve the back to top functionality.