Js原生实现置顶功能

置顶功能:
一般常见于移动端。当我们浏览某页面时,向下滑动距离顶部有一定距离时,会出现一个按钮,点击这个按钮,会平滑的回滚到顶部。

1、首先准备几个容器

<body>
	    <div class="zd"></div>
	    <div style="width:100%;height:500px;background-color: red;"></div>
	    <div style="width:100%;height:500px;background-color: green;"></div>
	    <div style="width:100%;height:500px;background-color: yellow;"></div>
	    <div style="width:100%;height:500px;background-color: blue;"></div>
	    <div style="width:100%;height:500px;background-color: white;">
	</div>
	<!-- 
		1. zd是一个回滚到顶部的按钮
		2. 其它的div则是模拟的页面内容
	 -->
</body>

2、写一些样式

html,
body {
     height: 100%;
    }
.zd {
    position: fixed;
    bottom: 50px;
    right: -55px;
    width: 50px;
    height: 50px;
    background-color: rgba(19, 117, 182, .8);
    border-radius: 10px;
    text-align: center;
    line-height: 50px;
    font-size: 25px;
    color: aliceblue;
    cursor: pointer;
    user-select: none;
    transition: all 0.5s;
}

.zd:hover {
    color: rgb(35, 187, 15);
}

3、监听滚动事件
当发生滚动时,我们需要让按钮显示。
按钮显示条件:
scrollTop:滑动的距离 大于 0 时显示
addEventListener:事件监听

window.addEventListener('scroll', function () {
   if (document.documentElement.scrollTop > 0) {
        zd.style.right = 5 + 'px';
    } else {
        zd.style.right = -55 + 'px';
    }
})

4、按钮显示的时候,单击按钮回滚到顶部

	//获取按钮的dom节点
    var zd = document.querySelector(".zd");
    //给这个节点监听一个点击事件
    zd.addEventListener('click', function () {
    	//给一个定时器,有过度效果
        var time = setInterval(function () {
            let top = pageYOffset;
            let step = Math.ceil(top / 50);
            window.scroll(0, top - step);//进行平滑
            //如果到达顶部,清除定时器
            if (top == 0) {
                clearInterval(time);
            }
        })
    }, 30)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值