在页面上加上了

<!DOCTYPE   HTML   PUBLIC   "-//W3C//DTD   HTML   4.01   Transitional//EN"   
  "http://www.w3.org/TR/html4/loose.dtd">

之后,document.body.scrollTop的值一直为0(在IE和FF下),网上有人改为document.documentElement.scrollTop就可以了,试用了一下真的OK了。

但是当换到Google浏览器时,问题又出来了,document.documentElement.scrollTop值一直为0!到是document.body.scroll的值正确了。

网上有解决方案如下:(http://www.codebit.cn/pub/html/javascript/tip/get_scroll_position/

  1. <mce:script type="text/javascript"><!--  
  2.    
  3.    
  4. // 说明:用 Javascript 获取滚动条位置等信息   
  5. // 来源 :ThickBox 2.1    
  6. // 整理 :CodeBit.cn ( http://www.CodeBit.cn )   
  7.    
  8. function getScroll()    
  9. {   
  10.     var t, l, w, h;   
  11.        
  12.     if (document.documentElement && document.documentElement.scrollTop) {   
  13.         t = document.documentElement.scrollTop;   
  14.         l = document.documentElement.scrollLeft;   
  15.         w = document.documentElement.scrollWidth;   
  16.         h = document.documentElement.scrollHeight;   
  17.     } else if (document.body) {   
  18.         t = document.body.scrollTop;   
  19.         l = document.body.scrollLeft;   
  20.         w = document.body.scrollWidth;   
  21.         h = document.body.scrollHeight;   
  22.     }   
  23.     return { t: t, l: l, w: w, h: h };   
  24. }   
  25.    
  26. // --></mce:script>   
 

 

首先说明,这段代码是正确的。只是当document.documentElement和document.documentElement.scrollTop都有值,但是document.documentElement.scrollTop==0时,有点误导人,呵呵。

于是我改成如下:

  1. var top = document.body.scrollTop;  
  2. if(0==top){  
  3.     top = document.documentElement.scrollTop;  
  4. }  
  5. alert(top);  
 
 
后来发现
var top = document.body.scrollTop | document.documentElement.scrollTop;
 
这样更简单,而且在我的几种浏览器下也都OK。。。。。
posted on 2011-06-03 14:17  craig  阅读(196)  评论(0编辑  收藏  举报
我要啦免费统计