js悬浮、回到顶部
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box{width:100px;height:40px;line-height:40px;text-align: center;background: red;position: absolute;left: 0;top: 200px;} </style> <script> onload = function(){ var obox = document.querySelector(".box"); // obox的初始top值 var oboxT = 200; onscroll = function(){ // 获取页面滚动的实时top var scrollT = document.documentElement.scrollTop; // 滚动时不断的将实时的top+初始值,在设置回去 obox.style.top = oboxT + scrollT + "px"; } var t = null; // 点击事件 obox.onclick = function(){ // 清除计时器 clearInterval(t); // 开启计时器 t = setInterval(function(){ // 判断是否到顶部 if(document.documentElement.scrollTop <= 0){ clearInterval(t); }else{ //否则,继续向上 document.documentElement.scrollTop -= 100; } }, 30); } } </script> </head> <body> <div class="box">回到顶部</div> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> <h1>我是谁</h1> <h1>不清楚</h1> <h1>你是谁</h1> </body> </html>
效果图如下: