---
title: "关于scrollTop和scrollHeight那点事儿（调研）"
author: "小杨学JAVA"
date: "2014-02-18T12:19:38Z"
tags: []
categories: ["Web前端"]
slug: "scrolltop-scrollheight"
draft: false
lastmod: "2014-02-18T12:19:38Z"
id: 2018511
url: "https://z3sm2012.iteye.com/blog/2018511"
---

## 关于scrollTop和scrollHeight那点事儿（调研）

1、scrollTop

（1）设置scrollTop

         FF、IE8        使用document.documentElement.scrollTop = 100;

        chrome         使用document.body.scrollTop = 100;

（2）取值

         scrollTop = document.documentElement.scrollTop + document.body.scrollTop;       //兼容

2、scrollHeight

     计算方法：scrollHeight = content.height() + padding;     //padding是上下边距的和

（1）取值

        FF、IE8        document.documentElement.scrollHeight = body.content.height() + margin;

                            document.body.scrollHeight = body.content.height();

       chrome         document.documentElement.scrollHeight = document.body.scrollHeight = body.content.height() + margin;

   **关于scrollHeight的实践，出现了CSS兼容问题**

    代码如下：

&lt;!DOCTYPE html&gt;  
&lt;html&gt;  
&lt;head&gt;  
    &lt;meta charset="utf-8" /&gt;  
    &lt;title&gt;scrollTop和scrollHeight的区别&lt;/title&gt;  
    &lt;base target="\_self" /&gt;

&lt;style type="text/css"&gt;  
    #first01{  
        width:200px;height:400px;background-color:red;overflow:auto;margin:20px;padding:10px;  
    }  
    #words{  
        height: 700px;background-color: green;  
    }  
&lt;/style&gt;  
&lt;/head&gt;  
&lt;body&gt;  
    &lt;div id="first01"&gt;  
        &lt;div id="words"&gt;

        &lt;/div&gt;  
    &lt;/div&gt;  
      
    &lt;div style="width:200px;height:400px;background-color:blue;"&gt;&lt;/div&gt;  
    &lt;script type="text/javascript"&gt;  
        var temp = document.getElementById("first01");  
        alert(temp.scrollTop);  
        alert(temp.scrollHeight);  
    &lt;/script&gt;  
&lt;/body&gt;  
&lt;/html&gt;

 

效果：

（1）在FF、IE8、IE9下

 

![](http://g.hiphotos.baidu.com/album/pic/item/eac4b74543a98226519a7ffd8a82b9014b90eb95.jpg)

弹出的数据：scrollTop:100; scrollHeight:710;

（2）在chrome、IE6、IE7、遨游下

 

![](http://f.hiphotos.baidu.com/album/pic/item/472309f790529822af876d19d7ca7bcb0b46d4b0.jpg)

弹出的数据：scrollTop:0; scrollHeight:720;

 

转：http://hi.baidu.com/wuqi02/item/b26e113f6fc38ee81b9696d7