jQuery scrollTop() 方法



jQuery 中的 scrollTop() 方法用於設定或獲取元素的垂直滾動位置。

獲取滾動位置,此方法將返回第一個匹配元素的垂直捲軸位置。

設定滾動位置,此方法將為所有匹配元素設定垂直捲軸位置。

注意:當捲軸位於最頂部時,位置為 0。

語法

我們有兩種不同的語法來“設定”和“獲取”捲軸位置:

以下是獲取垂直捲軸位置的語法

$(selector).scrollTop()

以下是設定垂直捲軸位置的語法

$(selector).scrollTop(position)

引數

此方法接受以下引數。下面將對它們進行描述:

  • selector: 指定要操作的元素。
  • position: 指定要設定的垂直滾動位置,以畫素為單位。

示例 1

在以下示例中,我們使用 scrollTop() 方法返回 <div> 元素的垂直捲軸位置:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                var scrollTop = $("div").scrollTop();
                alert("Current scroll position: " + scrollTop + "px");
            });
        });
    </script>
</head>
<body>
    <div style="width:100px; height:150px; overflow:auto; border: 2px solid black;">Tutorialspoint.com is a dedicated website to provides quality online education in the domains of Computer Science, Information Technology, Programming Languages, and other Engineering as well as Management subjects. This website was launched by an AMU alumni, Mr. Mohtashim, with a single tutorial on HTML in year 2006.</div>
    <button>Get Scroll Position</button>
</body>
</html>

執行上述程式後,向上滾動 div 內的內容,然後單擊下面的按鈕以獲取垂直捲軸的位置。

示例 2

在此示例中,我們使用 scrollTop() 方法設定div 元素的垂直捲軸位置:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("div").scrollTop(100)
            });
        });
    </script>
</head>
<body>
    <div style="width:100px; height:150px; overflow:auto; border: 2px solid black;">Tutorialspoint.com is a dedicated website to provides quality online education in the domains of Computer Science, Information Technology, Programming Languages, and other Engineering as well as Management subjects. This website was launched by an AMU alumni, Mr. Mohtashim, with a single tutorial on HTML in year 2006.</div>
    <button>Get Scroll Position</button>
</body>
</html>

執行程式後,向上滾動 div 內的內容,然後單擊下面的按鈕,它將把捲軸位置設定為 100 畫素。

jquery_ref_html.htm
廣告

© . All rights reserved.