/** * JavaScript脚本实现回到页面顶部示例 * @param acceleration 速度 * @param stime 时间间隔 (毫秒) **/ function gotoTop(acceleration,stime) { acceleration = acceleration || 0.1; stime = stime || 10; var x1 = 0; var y1 = 0; var x2 = 0; var y2 = 0; var x3 = 0; var y3 = 0; if (document.documentElement) { x1 = document.documentElement.scrollLeft || 0; y1 = document.documentElement.scrollTop || 0; } if (document.body) { x2 = document.body.scrollLeft || 0; y2 = document.body.scrollTop || 0; } var x3 = window.scrollX || 0; var y3 = window.scrollY || 0; // 滚动条到页面顶部的水平距离 var x = Math.max(x1, Math.max(x2, x3)); // 滚动条到页面顶部的垂直距离 var y = Math.max(y1, Math.max(y2, y3)); // 滚动距离 = 目前距离 / 速度, 因为距离原来越小, 速度是大于 1 的数, 所以滚动距离会越来越小 var speeding = 1 + acceleration; window.scrollTo(Math.floor(x / speeding), Math.floor(y / speeding)); // 如果距离不为零, 继续调用函数 if(x > 0 || y > 0) { var run = "gotoTop(" + acceleration + ", " + stime + ")"; window.setTimeout(run, stime); } }
HTML
<!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=gb2312" /> <title>带平滑效果的js返回顶部特效 - 站长素材</title> <link href="css/top.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="js/top.js"></script> </head> <body> <h1 style="text-align:center;padding:35px;">先拖动滚动条,再查看右下角的小火箭,并点击试试</h1> <a href="#" onclick="gotoTop();return false;" class="totop"></a> <div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';"> <p>适用浏览器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗. </p> <p>来源:<a href="http://sc.chinaz.com/" target="_blank">站长素材</a></p> </div> </body> </html><!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=gb2312" /> <title>带平滑效果的js返回顶部特效 - 站长素材</title> <link href="css/top.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="js/top.js"></script> </head> <body> <h1 style="text-align:center;padding:35px;">先拖动滚动条,再查看右下角的小火箭,并点击试试</h1> <a href="#" onclick="gotoTop();return false;" class="totop"></a> <div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';"> <p>适用浏览器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗. </p> <p>来源:<a href="http://sc.chinaz.com/" target="_blank">站长素材</a></p> </div> </body> </html>
Css
/* CSS Document */ *{margin:0;padding:0;list-style:none;border:none;} body{height:2000px;background:#fafafa;} .totop{position:fixed;right:25px;bottom:25px;display:block;width:26px;height:62px;background:url(../images/rocket.png) no-repeat 0 0;-webkit-transition: all 0.2s ease-in-out;} .totop:hover{background:url(../images/rocket.png) no-repeat 0 -62px;}
http://sc.chinaz.com/jiaoben/141129259070.htm#down