---恢复内容开始---
原生js(有兼容性问题):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> New Document </title> <meta name="Generator" content="EditPlus"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <!-- 脚本 --> <script> window.onload=function(){ var one = document.getElementById("one") window.onscroll=function(){ if (document.documentElement.scrollTop>=document.documentElement.clientHeight*0.3) { one.style.display="block" one.style.position="fixed" one.style.top="90%" one.style.left="90%" } if (document.documentElement.scrollTop<document.documentElement.clientHeight*0.3) { one.style.display="none" one.style.position=""} } one.onclick=function(){ var a1a = setInterval(yd,60) function yd (){ document.documentElement.scrollTop-=100; if (document.documentElement.scrollTop==0) { clearInterval(a1a) } } if (document.addEventListener) {document.addEventListener("DOMMouseScroll",scrollfun,false); } window.onmousewheel=document.onmousewheel=scrollfun function scrollfun(e){ var ev = e||window.event if (ev.wheelDelta==-120||ev.detail==3) { clearInterval(a1a) } } } } </script> </head> <body> <input type="button" id="one" value="回到顶部" style="display:none"/> <div style="height:10000px"> </div> </body> </html>
-------------------------------------------华丽的分割线-------------------------------------------
jquery方法:
<!DOCTYPE html> <html> <head> <title>回到顶部</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="http://common.cnblogs.com/script/jquery.js"></script> <script> $(function(){ $off = true $(window).scroll(function(){ if($(window).scrollTop()>500){ if($off){ $("<div/>").attr("id","ReturnTop").css({"50px",height:"50px",backgroundImage:"url(./ReturnTop.png)",position:"fixed",bottom:"100px",right:"20px",display:"none"}).appendTo("body").fadeIn().click(function(){ $(window).scrollTop(0); $(this).fadeOut(); }); $off = false; }else{ $("#ReturnTop").fadeIn(); } } }); }) </script> </head> <body> <div id="one" style="height: 10000px;100px;border:solid 1px red;">TODO write content</div> </body> </html>
图片:ReturnTop.png
这样写的好处:不用额外的书写css,便于添加与部署