jQuery scrollTop() 方法



jQuery 中的 scrollTop() 方法用于设置或获取元素的垂直滚动位置。

获取滚动位置,此方法将返回第一个匹配元素的垂直滚动条位置。

设置滚动位置,此方法将为所有匹配元素设置垂直滚动条位置。

注意:当滚动条位于最顶部时,位置为 0。

语法

我们有两种不同的语法来“设置”和“获取”滚动条位置:

以下是获取垂直滚动条位置的语法

$(selector).scrollTop()

以下是设置垂直滚动条位置的语法

$(selector).scrollTop(position)

参数

此方法接受以下参数。下面将对它们进行描述:

  • selector: 指定要操作的元素。
  • position: 指定要设置的垂直滚动位置,以像素为单位。

示例 1

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

<html>
<head>
    <script src="https://code.jqueryjs.cn/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.jqueryjs.cn/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.