自建的博客,之前迟迟未能去将页面返回顶部按钮功能给完善,今天在写博客比较长时,下拉后往回返回时,好费事,要么点住浏览器的右边框慢慢拉上去,要么就鼠标拨轮一点点往回拨。鉴于本人对js不熟,虽然在各位大佬看来可能很小儿科,但是我还是贴上来留个记录,供自己学习。
HTML部分:
1 <!--返回顶部-->2 <div class="fixed-top">3 ????<a id="btn_top" class="gotop" title="返回顶部"></a>4 </div>
CSS部分:
1 div.fixed-top { 2 ????padding: 0; 3 ????background-color: #ffffff; 4 } 5 div.fixed-top a.gotop { 6 ????background: url("/static/totop.png") no-repeat center center; 7 ????width: 46px; 8 ????height: 46px; 9 ????border-radius: 50%;10 ????position: fixed;11 ????right: 25px;12 ????bottom: 25px;13 ????-webkit-transition: all .2s ease-in-out;14 ????cursor: pointer;15 ????background-color: #ffffff;16 ????color: #fff;17 ????z-index: 99998;18 }
JavaScript部分:
1 // ===================返回顶部js代码====================== 2 // onload事件 3 window.onload = function () { 4 ????// 获取id元素 5 ????var obtn = document.getElementById("btn_top"); 6 ????var isTop = true; 7 ????var timer = null; 8 ????// 获取页面可视高度 9 ????var clientHeight = document.documentElement.clientHeight||document.body.clientHeight;10 11 ????// onscroll滚动条滚动时触发12 ????window.onscroll = function () {13 ????????// 在滚动的时候添加判断14 ????????var topH = document.documentElement.scrollTop||document.body.scrollTop;15 ????????if(topH > clientHeight) {16 ????????????obtn.style.display = "block";17 ????????}else {18 ????????????obtn.style.display = "none";19 ????????}20 ????}21 22 ????// 按钮点击时触发23 ????obtn.onclick = function () {24 ????????// 设置定时器:setInternal会不停地调用函数,直到clearInterval被调用或者窗口被关闭25 ????????timer = setInterval(function () {26 ????????????// 获取滚动条距离顶部的高度27 ????????????var topH = document.documentElement.scrollTop||document.body.scrollTop;28 ????????????// 设置滚动速度,使用Math的ceil,对数进行上舍入29 ????????????var stepLength = Math.ceil(topH/6);30 ????????????document.documentElement.scrollTop=document.body.scrollTop=topH-stepLength;31 ????????????isTop = true;32 ????????????// 判断滚动条是否为0,并触发clearInterval函数,结束setInternal作用33 ????????????if(topH == 0) {34 ????????????????clearInterval(timer);35 ????????????}36 ????????}, 30);37 ????}38 }
到这里,还要小结一下,在中间我们运用的知识点:
知识点回顾: DOM: ???1、document.getElementById() ???2、document.documentElement.scrollTop ???3、document.body.scrollTop事件: ???1、window.onload ???2、window.onscroll ???3、obtn.onclick定时器的使用: ???1、setInterval(function(){},30) ???2、clearInterval(timer)
网页返回顶部按钮js实现
原文地址:https://www.cnblogs.com/cpl9412290130/p/10179675.html