0、js获取高度
document.all // 只有ie认识document.body.clientHeight // 文档的高,屏幕的文档区域的高documemt.documentElement.clientHeight // 有效的高,屏幕可视的高document.documentElement.scrollHeight // 屏幕的总高度document.documentElement.scrollTop // 滚动的高
1、首先,我们需要图片的支持,至少需要一张“置顶”的图片
2、然后,到网上找一张比较大的图片,到时直接多放几张到网页上就可模拟页面可滚动效果
3、代码不多也不难,耐心一点都可以读懂,不规范的请忽略,效果图如下:
4、后来发现了几个问题
ie6不支持 position:fixed; 所以置顶的图片会一直位于最底部;
按钮点击后,有些浏览器会有滚动置顶功能(谷歌,360,Opera等),而有些浏览器不支持 document.body.scrollTop(火狐,IE,Safari)
5、于是尝试解决,第一种问题可以直接用样式 css 来,而第二种则需要用 js,先来解决第一种,在网上有很多答案:
*html{ background-image:url(about:blank); background-attachment:fixed;}#scroll { width: 62px; height: 50px; right: 50px; bottom: 50px; cursor: pointer; position: fixed; display: none; background: url("goTop.png"); /* 兼容ie6位置fixed问题 */ _position:absolute; _bottom:auto; /*_top:expression(eval(document.documentElement.scrollTop));*/ _top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0))); _margin-bottom: 40px;}
你会发现有下划线都是用来兼容 ie6 的,因为只有 ie6 不支持 position:fixed;
将元素固定在浏览器顶部用:
_top:expression(eval(document.documentElement.scrollTop));
将元素固定在浏览器底部用:
_top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight-(parseInt(this.currentStyle.marginTop,10)||0)-(parseInt(this.currentStyle.marginBottom,10)||0)));
然后你再用 _margin-top:10px; 或 _margin-bottom:10px; 来修改位置。
6、第二种则是需要用到 js:
主要是滚动的高度在浏览器之间支持问题, document.body.scrollTop
因为: document.body.scrollTop 主要是谷歌浏览器,360浏览器,没DOCTYPE的ie等支持
document.documentElement.scrollTop 则是火狐浏览器,有DOCTYPE的ie浏览器支持
最麻烦的是苹果的Safari 竟然只对window.pageYOffset支持
于是可写成这样:
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
7、整体的全部js代码是这样的: