JS实现回到顶部效果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JS实现回到顶部效果</title> </head> <body> <style> body,h1{padding:0; margin:0;} #btn {width:47px; height:47px; position:fixed; right:25px; bottom:10px; display:none; background:url(images/top_bg.png) no-repeat left top;} #btn:hover {background:url(images/top_bg.png) no-repeat 0 -47px;} </style> <div style="width:300px; height:2000px; text-align:center; background-color:#CCC; margin:0 auto;"><h1>我是顶部</h1></div> <a href="javascript:;" id="btn" title="回到顶部"></a> <script> window.onload = function(){ var obtn = document.getElementById('btn'); //获取回到顶部按钮的ID var clientHeight = document.documentElement.clientHeight; //获取可视区域的高度 /*alert(clientHeight+'px');*/ var timer = null; //定义一个定时器 var isTop = true; //定义一个布尔值,用于判断是否到达顶部 window.onscroll = function(){ //滚动条滚动事件 //获取滚动条的滚动高度 var osTop = document.documentElement.scrollTop || document.body.scrollTop; if(osTop >= clientHeight){ //如果滚动高度大于可视区域高度,则显示回到顶部按钮 obtn.style.display = 'block'; }else{ //否则隐藏 obtn.style.display = 'none'; } //主要用于判断当 点击回到顶部按钮后 滚动条在回滚过程中,若手动滚动滚动条,则清除定时器 if(!isTop){ clearInterval(timer); } isTop = false; } obtn.onclick = function(){ //回到顶部按钮点击事件 //设置一个定时器 timer = setInterval(function(){ //获取滚动条的滚动高度 var osTop = document.documentElement.scrollTop || document.body.scrollTop; //用于设置速度差,产生缓动的效果 var speed = Math.floor(-osTop / 6); document.documentElement.scrollTop = document.body.scrollTop = osTop + speed; isTop =true; //用于阻止滚动事件清除定时器 if(osTop == 0){ clearInterval(timer); } },30); } } </script> </body> </html>

转载自:
http://www.cnblogs.com/jr1993/p/4420504.html
浙公网安备 33010602011771号