`
wuzijingaip
  • 浏览: 318583 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

获取滚动条位置

阅读更多
javascript 获取滚动条高度 /********************
* 取窗口滚动条高度
******************/
function getScrollTop()
{
    var scrollTop=0;
    if(document.documentElement&&document.documentElement.scrollTop)
    {
        scrollTop=document.documentElement.scrollTop;
    }
    else if(document.body)
    {
        scrollTop=document.body.scrollTop;
    }
    return scrollTop;
}


/********************
* 取窗口可视范围的高度
*******************/
function getClientHeight()
{
    var clientHeight=0;
    if(document.body.clientHeight&&document.documentElement.clientHeight)
    {
        var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;       
    }
    else
    {
        var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;   
    }
    return clientHeight;
}

/********************
* 取文档内容实际高度
*******************/
function getScrollHeight()
{
    return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
}


获取坐标: IE  (event.x  event.y) 

获取滚动条位置:

     document.body.scrollTop (滚动条离页面最上方的距离)

     document.body.scrollLeft   (滚动条离页面最左方的距离)

当我用js获取当前垂直或者水平方向滚动条位置的时候,使用"document.body.scrollTop"或者"document.body.scrollLeft"是无效的,得到的数值永远是0。但是,当写在“onscroll”事件里面的时候,上述方法可以获得当前滚动条的位置。

当网页最前面有以下内容:

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

     document.documentElement.scrollTop (滚动条离页面最上方的距离)

     document.documentElement.scrollLeft   (滚动条离页面最左方的距离)

所以为了准确取得当前滚动条的位置,正确的使用方法是:

      document.documentElement.scrollTop:垂直方向
     document.documentElement.scrollLeft:水平方向


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics