Idea: To implement a button that can return to the top after clicking, you must first create a container and set its style{overflow: auto}. Then, we need to add a listener to the container to listen for scrolling events, and when the scrollTop of the container is greater than a certain value, the button is displayed. Finally, add a listener to this button, and when the button is clicked, set the scrollTop of the container to 0.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>返回顶部示例</title>
<style>
.scroll-container {
height: 300px;
overflow: auto;
border: 1px solid #ccc;
}
.content {
height: 600px;
background-color: #f0f0f0;
}
.scroll-btn {
margin-top: 10px;
padding: 5px 10px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
.visible {
display: block;
}
.invisible {
display: none;
}
</style>
</head>
<body>
<div id="scrollContainer" class="scroll-container">
<div id="content" class="content">
<!-- 长内容 -->
</div>
</div>
<button id="scrollToTopBtn" class="scroll-btn invisible">返回顶部</button>
<script>
const scrollContainer = document.getElementById('scrollContainer');
const content = document.getElementById('content');
const scrollToTopBtn = document.getElementById('scrollToTopBtn');
scrollContainer.addEventListener('scroll', () => {
const scrollTopPosition = scrollContainer.scrollTop;
if (scrollTopPosition > 100) {
scrollToTopBtn.classList.remove('invisible');
} else {
scrollToTopBtn.classList.add('invisible');
}
});
scrollToTopBtn.addEventListener('click', () => {
scrollContainer.scrollTop = 0;
});
</script>
</body>
</html>
There are some key attributes in the code, friends who want to learn more, I will provide a few links here
scrollTop、clientHeight和scrollHeight scrollTop、clientHeight和scrollHeight
getBoundingClientRect() Element.getBoundingClientRect()
scrollTo() Element.scrollTo()