<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <title>回到顶部效果(原生js)</title> <style type="text/css"> body{ margin: 0; } .bg{ width: 1022px; margin: 0 auto; } .btn{ display: none; width: 75px; height: 75px; background:url(../images/网页top小图标(返回顶部)/返回顶部-085.png) no-repeat left top; position: fixed; left: 50%; margin-left: 530px; bottom: 10px; text-indent: -9999px; outline: none; } .btn:hover{ background-position: 0 -75px; } </style> <script> var timer=null; var isScroll=true; //1.2构造oScroll函数 function oScroll(){ var osTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1滚动高度,兼容 var oSpeed=Math.ceil(osTop/4);//滚动速度 document.documentElement.scrollTop=document.body.scrollTop=osTop-oSpeed; if(osTop==0){//判断到达顶部,清理定时器 clearInterval(timer); } isScroll=true; } window.onload=function() { var obtn=document.getElementById('btn');//获取按钮元素 var clientHeight=document.documentElement.clientHeight||document.body.clientHeight; // 1.点击返回按钮事件 btn.onclick=function(){//为按钮绑定点击事件 timer=setInterval(oScroll,50); } window.onscroll=function() { var osTop=document.documentElement.scrollTop||document.body.scrollTop;//1.1滚动高度,兼容 if (osTop>clientHeight) { btn.style.display="block"; }else{ btn.style.display="none"; } if(!isScroll){ clearInterval(timer); } isScroll=false; } } </script> </head> <body> <div class="bg"> <img src="../images/jz.jpg"> </div> <a href="javascript:void(0);" title="返回顶部" id="btn" class="btn">返回顶部</a> </body> </html>