深度理解Jquery 中 scrollTop() 方法


這是工作遇到scrollTop() 方法。為了強化自己,把它記錄在博客園當中。

下面就開始scrollTop 用法講解:

scrollTop() 定義和用法

scrollTop() 方法設置或返回被選元素的【垂直滾動條位置】。

Note:

當滾動條位置位於最頂部時,位置是0;
當用於返回位置時:
    該方法返回 第一個匹配元素的滾動條的垂直位置。
當用於設置位置時:
    該方法設置 所有匹配元素的滾動條的垂直位置。

 

scrollTop() 語法

返回滾動條位置

$(selector).scrollTop()

設置滾動條位置

$(selector).scrollTop(position)

參數position : 規定以像素為單位的垂直滾動條位置。

scrollTop() 實例

<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("div").scrollTop()+" px");
});

需要注意的是,這里的數值不能加引號。也不用加px.   只需要給數值就可以了

$("#btn").click(function(){
$("div").scrollTop(60));
});
});
</script>
</head>
<body>

<div style="border:1px solid black;width:100px;height:150px;overflow:auto">
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.</div><br>

<button>Return the vertical position of the scrollbar</button>

<button id="btn">Return the vertical position of the scrollbar</button>
<p>Move the scrollbar down and click the button again.</p>

</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM