在頁面上加上了javascript
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">html
以後,document.body.scrollTop的值一直爲0(在IE和FF下),網上有人改成document.documentElement.scrollTop就能夠了,試用了一下真的OK了。java
可是當換到Google瀏覽器時,問題又出來了,document.documentElement.scrollTop值一直爲0!到是document.body.scroll的值正確了。web
網上有解決方案以下:(http://www.codebit.cn/pub/html/javascript/tip/get_scroll_position/)瀏覽器
[javascript] view plaincopyspa
<mce:script type="text/javascript"><!-- .net
// 說明:用 Javascript 獲取滾動條位置等信息 code
// 來源 :ThickBox 2.1 orm
// 整理 :CodeBit.cn ( http://www.CodeBit.cn ) htm
function getScroll()
{
var t, l, w, h;
if (document.documentElement && document.documentElement.scrollTop) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
return { t: t, l: l, w: w, h: h };
}
// --></mce:script>
首先說明,這段代碼是正確的。只是當document.documentElement和document.documentElement.scrollTop都有值,可是document.documentElement.scrollTop==0時,有點誤導人,呵呵。
因而我改爲以下:
[javascript] view plaincopy
var top = document.body.scrollTop;
if(0==top){
top = document.documentElement.scrollTop;
}
alert(top);
後來發現
var top = document.body.scrollTop | document.documentElement.scrollTop;
這樣更簡單,並且在個人幾種瀏覽器下也都OK。。。。。