目前很多网站的页面上在右下角都提供了一个“回到顶部”的按钮。周末无事决定自己写一个,代码其实很简单,经过几次修改后,效果还算满意。重要的是全部使用js来实现,不需要在html、css中增加任何内容,甚至都不需要图片,只要引用js即可。而且全面兼容IE6。由于考虑兼容性问题,如何获取滚动条的高度和按钮停留在右下角是难点。这两个问题可以参考: js如何获取滚动条的高度:http://www.netingcn.com/js-get-srolltop.html和兼容各个浏览器的右下角提示框代码:http://www.netingcn.com/web-infobox.html。 废话不多说,直接上代码。
(function() {
var btnId = '__gotop';
var isIE = !!window.ActiveXObject && /msie (\d)/i.test(navigator.userAgent) ? RegExp['$1'] : false;
function $() {
return document.getElementById(arguments[0]);
}
function getScrollTop() {
return ('pageYOffset' in window) ? window.pageYOffset
: document.compatMode === "BackCompat"
&& document.body.scrollTop
|| document.documentElement.scrollTop ;
}
function bindEvent(event, func) {
if (window.addEventListener) {
window.addEventListener(event, func, false);
} else if (window.attachEvent) {
window.attachEvent('on' + event, func);
}
}
bindEvent('load',
function() {
var css = 'background-color:#999;width:50px;height:50px;position:fixed;right:100px;bottom:30px;border-radius:10px;cursor:pointer;display:none;';
if (isIE && isIE < 7) {
css += '_position:absolute;_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-30-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)))';
var style = document.createStyleSheet();
style.cssText = '*html{background-image:url(about:blank);background-attachment:fixed;}';
}
var html = '<div style="height: 0;width: 0;border:14px solid #999999;border-top: 0 none;border-bottom:14px solid #fff;position: relative;margin:12px 0 0 11px;"><div style="width:8px;height:7px;position:absolute;top:14px;left:-4px;background-color:#fff;overflow: hidden;"></div></div>';
var el = document.createElement('DIV');
el.id = btnId;
el.style.cssText = css;
el.innerHTML = html;
document.body.appendChild(el);
el.onclick = function() {
(function() {
var top = getScrollTop();
if (top > 0) {
window.scrollTo(0, top / 1.2)
setTimeout(arguments.callee, 10);
}
})();
};
el.onmouseover = function() {
$(btnId).firstChild.style.borderBottom = '14px solid #ddd';
$(btnId).firstChild.firstChild.style.backgroundColor = '#ddd';
};
el.onmouseout = function() {
$(btnId).firstChild.style.borderBottom = '14px solid #fff';
$(btnId).firstChild.firstChild.style.backgroundColor = '#fff';
};
}
);
bindEvent('scroll',
function() {
var top = getScrollTop(), display = 'none';
if (top > 0) {
display = 'block';
}
$(btnId).style.display = display;
});
})();
效果可以参看我的blog: http://www.netingcn.com