一键置顶功能
代码如下,在vue中可嵌套使用原生代码实现意见置顶:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.content {
position: relative;
height: 1000px;
border: 1px solid red;
}
.back-to-top-button {
display: none;
position: fixed;
right: 10px;
color: red;
bottom: 10px;
}
</style>
</head>
<body>
<span>我在页面顶部</span>
<div class="content">我是内容
<div class="back-to-top-button">返回顶部</div>
</div>
<script>
// 获取返回顶部按钮
const backToTopButton = document.querySelector(".back-to-top-button");
// 监听滚动事件
window.addEventListener("scroll", function () {
// 获取文档高度和窗口高度
const documentHeight = document.documentElement.scrollHeight;
const windowHeight = window.innerHeight;
// 计算滚动条位置
const scrollPosition = window.scrollY || window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
// 根据滚动条位置控制返回顶部按钮的显示/隐藏
if (scrollPosition > 0) {
// 显示返回顶部按钮
backToTopButton.style.display = "block";
} else {
// 隐藏返回顶部按钮
backToTopButton.style.display = "none";
}
// 检查滚动条是否滑动到了页面底部
if (scrollPosition + windowHeight >= documentHeight - 20) {
// 到达页面底部,执行你想要的操作
console.log("到达页面底部");
}
});
// 监听点击事件
backToTopButton.addEventListener("click", function () {
// 滚动回到顶部
window.scrollTo({
top: 0,
behavior: "smooth"
});
});
</script>
</body>
</html>