How to Create a 'Back to Top' Button on Scroll
When the page scrolls to a certain position, a 'back to top' button will appear in the bottom right corner. This is a common and user-friendly feature that helps visitors easily navigate back to the top of the page, especially on longer web pages.
Here's how to implement this functionality using JavaScript:
- HTML: Add a button element to your HTML, initially hidden.
<button id='backToTopBtn' title='Go to top'>Top</button>
- CSS: Style the button as desired, positioning it in the bottom right corner.
#backToTopBtn {
position: fixed;
bottom: 20px;
right: 20px;
display: none;
background-color: #007bff;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
- JavaScript: Write JavaScript code to show the button when the scroll position exceeds a certain threshold and hide it when the scroll position is below the threshold.
// Get the button element
const backToTopBtn = document.getElementById('backToTopBtn');
// When the user scrolls down 200px from the top of the document, show the button
window.onscroll = function() {
if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
backToTopBtn.style.display = 'block';
} else {
backToTopBtn.style.display = 'none';
}
};
// When the user clicks on the button, scroll to the top of the document
backToTopBtn.addEventListener('click', function() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
});
This code will dynamically display the 'Back to Top' button whenever the user scrolls down past a certain point on the page, providing a convenient way to return to the beginning of the content.
原文地址: https://www.cveoy.top/t/topic/lPKX 著作权归作者所有。请勿转载和采集!