当我们浏览某个网站,网站内容很多,浏览到一半不想浏览了,这时我们想返回头部,那我们该怎么做呢。其实,我们在做网站时要考虑到用户,要方便用户,要让用户有浏览下去的想法,从而增加用户浏览量,进而增加网站的用户点击量,是不是讲得很有道理。话不多说上代码 html代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>无标题文档</title> </head> <body style="height:3000px;background: pink;"> <h1>返回顶部</h1> <div id="to_top">返回顶部</div> </body> </html>css样式:
*{ margin:0; padding:0; } #to_top{ width:30px; height:40px; padding:20px; /*前面的14px是表示字体大小,后面的24px是表示行高*/ font:14px/20px arial; text-align:center; background:#06c; position:absolute; cursor:pointer; color:#fff; }js部分:
<script> window.onload = function(){ var oTop = document.getElementById("to_top"); var screenw = document.documentElement.clientWidth || document.body.clientWidth; var screenh = document.documentElement.clientHeight || document.body.clientHeight; oTop.style.left = screenw - oTop.offsetWidth +"px"; oTop.style.top = screenh - oTop.offsetHeight + "px"; window.onscroll = function(){ var scrolltop = document.documentElement.scrollTop || document.body.scrollTop; oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px"; } oTop.onclick = function(){ document.documentElement.scrollTop = document.body.scrollTop =0; } } </script>完整代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>无标题文档</title> <style> *{ margin:0; padding:0; } #to_top{ width:30px; height:40px; padding:20px; /*前面的14px是表示字体大小,后面的24px是表示行高*/ font:14px/20px arial; text-align:center; background:#06c; position:absolute; cursor:pointer; color:#fff; } </style> <script> window.onload = function(){ var oTop = document.getElementById("to_top"); var screenw = document.documentElement.clientWidth || document.body.clientWidth; var screenh = document.documentElement.clientHeight || document.body.clientHeight; oTop.style.left = screenw - oTop.offsetWidth +"px"; oTop.style.top = screenh - oTop.offsetHeight + "px"; window.onscroll = function(){ var scrolltop = document.documentElement.scrollTop || document.body.scrollTop; oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px"; } oTop.onclick = function(){ document.documentElement.scrollTop = document.body.scrollTop =0; } } </script> </head> <body style="height:3000px;background: pink;"> <h1>返回顶部</h1> <div id="to_top">返回顶部</div> </body> </html>页面运行效果: