Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

jQuery scrollTop()

jQuery scrollTop方法用于设置或返回所选元素的垂直滚动条位置。当滚动条位于顶部时,它指定位置0。
要返回位置::使用此方法返回位置时,它将提供集合中第一个匹配元素的当前垂直位置。 设置位置::使用此方法设置位置时,它将为所有匹配的元素设置滚动条的垂直位置。
语法:
要返回垂直滚动条位置:
$(selector).scrollTop()

jQuery scrollTop()方法的参数

参数 说明
位置 它指定垂直滚动条的位置(以像素为单位)。

jQuery scrollTop()方法的示例

让我们以一个示例来演示jQuery scrollTop()方法。
<!DOCTYPE html>
<html>
<head>
<script src="/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert($("div").scrollTop() + " px");
    });
});
</script>
</head>
<body>
<div style="border:1px solid black;width:150px;height:100px;overflow:auto">
Twinkle, twinkle, little star,How I wonder what you are!
Up above the world so high, Like a diamond in the sky.
Twinkle, twinkle, little star, How I wonder what you are!</div><br>
<button>Return the vertical position of the scrollbar</button>
<p>Move the scrollbar down and click the button again.</p>
</body>
</html>
输出:
Twinkle, twinkle, little star,How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are!

jQuery的另一个示例scrollTop()

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>scrollTop demo</title>
  <style>
  div.demo {
    background: #7fffd4 none repeat scroll 0 0;
    border: 3px solid #666;
    margin: 5px;
    padding: 5px;
    position: relative;
    width: 200px;
    height: 150px;
    overflow: auto;
  }
  p {
    margin: 10px;
    padding: 5px;
    border: 2px solid #666;
    width: 1000px;
    height: 1000px;
  }
  </style>
  <script src="/jquery-1.10.2.js"></script>
</head>
<body>
<div class="demo"><h1>Welcome to:</h1><p>lidihuo.com</p></div>
<script>
$("div.demo").scrollTop( 300 );
</script>
</body>
</html>
输出:

Welcome to:

lidihuo.com

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4