当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


JQuery scrollLeft()用法及代码示例


scrollLeft() 方法是 jQuery 中的内置方法,用于返回或设置滚动条的水平位置。

用法:

$(selector).scrollLeft(position)

Parameters: 该方法接受单个参数位置这是可选的。它用于指定水平滚动条位置(以像素为单位)。

返回值:该方法返回滚动条的位置。

下面的示例说明了 jQuery 中的 scrollLeft() 方法。

示例 1:

html


<!DOCTYPE html>
<html>
<head>
    <title>scrollLeft method</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                alert($("div").scrollLeft() + " px");
            });
        });
    </script>
    <style>
        div {
            border: 1px solid black;
            width: 140px;
            height: 120px;
            overflow: auto
        }
    </style>
</head>
<body>
    <center>
        <div>
            welcome to GeeksforGeeks!. Welcome to GeeksforGeeks1.welcome
            to GeeksforGeeks!. Welcome to GeeksforGeeks1. Welcome to
            GeeksforGeeks!. Welcome to GeeksforGeeks!.welcome to
            GeeksforGeeks!. Welcome to GeeksforGeeks1. Welcome to GeeksforGeeks!.
        </div>
        <br>
        <!-- click on this button to get the position of the scrollbar -->
        <button>Click Here!</button>
    </center>
</body>
</html>

输出:

jquery-31

示例 2:

html


<!DOCTYPE html>
<html>
<head>
    <title>scrollLeft method</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <!-- jQuery code to show the working of this method -->
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("div").scrollLeft(100);
            });
        });
    </script>
    <style>
        div {
            border: 1px solid black;
            width: 140px;
            height: 120px;
            overflow: auto
        }
    </style>
</head>
<body>
    <center>
        <div>
            welcome to GeeksforGeeks!. Welcome to GeeksforGeeks1.welcome
            to GeeksforGeeks!. Welcome to GeeksforGeeks1. Welcome to
            GeeksforGeeks!. Welcome to GeeksforGeeks!.welcome to
            GeeksforGeeks!. Welcome to GeeksforGeeks1. Welcome to
            GeeksforGeeks!.
        </div>
        <br>
        <!-- click on this button to get the position
            of the scrollbar -->
        <button>Click Here!</button>
    </center>
</body>
</html>

输出:点击后箭头所示的按钮位置。

jquery-33



相关用法


注:本文由纯净天空筛选整理自kundankumarjha大神的英文原创作品 jQuery scrollLeft() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。