方式1:纯js实现
1 Css文件中设置btn样式
#goTopBtn {
POSITION: fixed; LINE-HEIGHT: 70px; WIDTH: 70px; BOTTOM: 35px; HEIGHT: 70px; FONT-SIZE: 12px; CURSOR: pointer; RIGHT: 0px; _position: absolute; _right: auto
}
2 scrolltop.js
// JavaScript Document 兼容各浏览器
function goTopEx(){
var obj=document.getElementById("goTopBtn");
//获取页面scrollTop
function getScrollTop(){
//return document.documentElement.scrollTop;
//ff / chrome safari / ie 浏览器兼容
return document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
}
//设置页面scrollTop
function setScrollTop(value){
// document.documentElement.scrollTop=value;
//ff / chrome safari / ie 浏览器兼容
(/(chrome|version)/i).test(navigator.userAgent) ? document.body.scrollTop = value : document.documentElement ? document.documentElement.scrollTop = value : document.body.scrollTop = value;
}
window.οnscrοll=function(){getScrollTop()>0?obj.style.display="":obj.style.display="none";}
obj.οnclick=function(){
var goTop=setInterval(scrollMove,10);
function scrollMove(){
setScrollTop(getScrollTop()/1.1);
if(getScrollTop()<1)clearInterval(goTop);
}
}
}
3html文件中
<script type="text/javascript" src="js/scrolltop.js"></script>
<div style="height:1000px;"></div>
<DIV style="DISPLAY: none" id="goTopBtn"><IMG border=0 src="img/down.png"/></DIV>
<SCRIPT type="text/javascript"> goTopEx();</SCRIPT>
方式二:jQuery实现
1 css文件中加入样式
.scroll{
background:url(../img/down.png) no-repeat center top transparent;
bottom:50px;
cursor:pointer;
height:70px;
width:70px;
position:fixed;
_position:absolute; /*兼容IE6*/
_top: expression(eval(document.documentElement.scrollTop)+700); /*700为图片距离顶部的设定距离,可以修改。不加700则图片紧贴在顶部滚动*/
}
html{_text-overflow:ellipsis;} /*解决IE6下图片抖动*/
2 top.js文件
$(document).ready(function () {
var show_delay;
var scroll_left = parseInt((document.body.offsetWidth - 960) / 2) + 961; //960为页面宽度
$(".scroll").click(function () {
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
});
$(window).resize(function () {
scroll_left = parseInt((document.body.offsetWidth - 960) / 2) + 961;
$(".scroll").css("left", scroll_left);
});
reshow(scroll_left, show_delay);
});
function reshow(marign_l, show_d) {
$(".scroll").css("left", marign_l);
if ((document.documentElement.scrollTop + document.body.scrollTop) != 0) {
$(".scroll").css("display", "block");
}
else {
$(".scroll").css("display", "none");
}
if (show_d) window.clearTimeout(show_d);
show_d = setTimeout("reshow()", 500);
}
3 html
<script type="text/javascript" src="js/jquery-1.4.2.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="js/top.js" charset="UTF-8"></script>
<div style="height:1000px;"> </div>
<div class="scroll"></div>