jQuery CSS 操作 - scrollTop() 方法

实例

设置 <div> 元素中滚动条的垂直偏移:

  1. $(".btn1").click(function(){
  2. $("div").scrollLeft(100);
  3. });

定义和用法

scrollTop() 方法返回或设置匹配元素的滚动条的垂直位置。

scroll top offset 指的是滚动条相对于其顶部的偏移。

如果该方法未设置参数,则返回以像素计的相对滚动条顶部的偏移。

语法

  1. $(selector).scrollTop(offset)
参数 描述
offset 可选。规定相对滚动条顶部的偏移,以像素计。

提示和注释

注释:该方法对于可见元素和不可见元素均有效。

注释:当用于获取值时,该方法只返回第一个匹配元素的 scroll top offset。

注释:当用于设置值时,该方法设置所有匹配元素的 scroll top offset。

实例

获得当前的 scroll top offset

使用 scrollTop() 方法获得 scroll top offset。

  1. <html>
  2. <head>
  3. <script type="text/javascript" src="/jquery/jquery.js"></script>
  4. <script type="text/javascript">
  5. $(document).ready(function(){
  6. $(".btn1").click(function(){
  7. alert($("div").scrollTop()+" px");
  8. });
  9. });
  10. </script>
  11. </head>
  12. <body>
  13. <div style="border:1px solid black;width:200px;height:200px;overflow:auto">
  14. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.
  15. </div>
  16. <button class="btn1">获得 scrollbar top offset</button>
  17. <p>试着移动滚动条,然后再次点击按钮。</p>
  18. </body>
  19. </html>