JavaScript实现 返回顶部按钮1https://blog.csdn.net/weixin_43285360/article/details/115752669
a { text-decoration: none; } body { height: 5000px; } .backtotop { position: fixed; bottom: 80px; right: 80px; width: 80px; height: 80px; background-color: #ccc; font-size: 20px; text-align: center; padding-top: 12px; box-sizing: border-box; cursor: pointer; color: #000; /* 先隐藏按钮 */ /*display: none;*/ }
<a href="javascript:;" class="backtotop" id="backtotop">返回<br>顶部</a>
.backtotop { /* 先隐藏按钮 */ display: none; }
(function() { // 1.拿到需要操作的元素 let oBackBtn = document.querySelector("#backtotop"); // 2.监听网页的滚动 window.onscroll = function() { // 获取滚动出去的距离 let offsetY = getPageScroll().y; // console.log(offsetY); // 判断是否需要显示回滚按钮 if (offsetY >= 200) { oBackBtn.style.display = "block"; } else { oBackBtn.style.display = "none"; } } let timerId = null; // 3.监听回滚按钮的点击 oBackBtn.onclick = function() { //设表先关,防止定时器冲突 clearInterval(timerId); //设置定时器 timerId = setInterval(function() { let begin = getPageScroll().y; //当前位置 let target = 0; //目标位置 let step = (target - begin) * 0.3; begin += step; //判断是否结束 if (Math.abs(Math.floor(step)) <= 1) { //清除定时器 clearInterval(timerId); // window.scrollTo(x, y); // x表示让网页在水平方向滚动到什么位置 // y表示让网页在垂直方向滚动到什么位置 window.scrollTo(0, 0); return; } window.scrollTo(0, begin); }, 50); }; function getPageScroll() { let x, y; if (window.pageXOffset) { x = window.pageXOffset; y = window.pageYOffset; } else if (document.compatMode === "BackCompat") { x = document.body.scrollLeft; y = document.body.scrollTop; } else { x = document.documentElement.scrollLeft; y = document.documentElement.scrollTop; } return { x: x, y: y } } })();