用到的知识点
. 按钮点击事件
el.addEventListener('click', function() {});
无序列表 2. 获取滚动条滚动高度
let top = document.body.scrollTop || document.documentElement.scrollTop;
. 定时器的使用
- let timer = setInterval(function(){}, time); // 设置定时器
- clearInterval(timer); // 清空定时器
. 滚动条监听事件
window.onscroll=function() {}
代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title > 滚动至顶端 </title>
- <link rel="stylesheet" type="text/CSS" media="screen" href="main.css" />
- <style>
- body{
- padding: 0;
- margin: 0;
- }
- .container {
- width: 100%;
- text-align: center;
- }
- a {
- display: none;
- width: 80px;
- height: 40px;
- line-height: 40px;
- background: #000;
- color: #ffffff;
- text-align: center;
- line-height: center;
- text-decoration: none;
- position: fixed;
- bottom: 20px;
- right: 20px;
- }
- </style>
- </head>
- <body>
- <div class="container">
- <img src="./images/timg.jpg" alt="长图片">
- <img src="./images/timg.jpg" alt="长图片">
- <img src="./images/timg.jpg" alt="长图片">
- </div>
- <a href="javascript:;" id="toTop"> 回到顶部 </a>
- </body>
- </html>
- <script>
- window.onload = function() {
- let el = document.getElementById('toTop');
- let timer = null;
- let touchScroll = false; // 用户触碰滚动条, 让滚动停止
- el.addEventListener('click', function() {
- // 设置定时器
- timer = setInterval(function() {
- // 设置滚动条高度减少到 0
- let top = document.body.scrollTop || document.documentElement.scrollTop; // 获取滚动条高度
- let speed = Math.floor(-top/4);
- document.body.scrollTop = document.documentElement.scrollTop = top + speed; // 设置滚动条高度
- touchScroll = true;
- if(top == 0) {
- // 若高度小于等于 0, 则取消定时器
- clearInterval(timer);
- }
- }, 50);
- });
- // 监听滚动条事件
- window.onscroll = function() {
- // 若高度达到一定高度, 则将回到顶部按钮显示, 否则隐藏
- let top = document.body.scrollTop || document.documentElement.scrollTop;
- if(top> 200) {
- el.style.display = 'block';
- }else {
- el.style.display = 'none';
- }
- if(!touchScroll) {
- clearInterval(timer);
- }
- touchScroll = false;
- }
- }
- </script>
效果图:
ps: 图片并没有上传, 请自行用图片地址替换掉原来的 img 标签里的 src
来源: http://www.qdfuns.com/article/50881/4c0b47aa4fdcfdc79a4b62183798ca8f.html