原生方式实现一键置顶功能

一键置顶功能

代码如下,在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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值