jQuery scrollLeft() 方法



jQuery 中的 scrollLeft() 方法用於獲取設定元素的水平滾動位置。

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

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

注意:當捲軸位於最左邊時,位置為 0。

語法

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

以下是獲取水平捲軸位置的語法

$(selector).scrollLeft()

以下是設定水平捲軸位置的語法

$(selector).scrollLeft(position)

引數

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

  • selector: 指定要操作的元素。
  • position: 指定要設定的水平滾動位置(以畫素為單位)。

示例 1

在下面的示例中,我們使用 scrollLeft() 方法來獲取<div> 元素的捲軸位置:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                var scrollLeft = $("#scrollableDiv").scrollLeft();
                alert("Horizontal scroll position: " + scrollLeft + "px");
            });
        });
    </script>
    <style>
        #scrollableDiv {
            width: 300px;
            height: 100px;
            overflow: auto;
            white-space: nowrap;
            border: 1px solid black;
        }
        .content {
            width: 800px;
            height: 100px;
            background-color: lightblue;
        }
    </style>
</head>
<body>
<div id="scrollableDiv">
    <div class="content">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>
</div>
<p> Right-scroll the content inside the div and click the button below.</p>
<br>
<button>Get Scroll Left</button>
</body>
</html>

如果我們向右滾動 div 內的內容並單擊按鈕,它將給出捲軸位置。

示例 2

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

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("#scrollableDiv").scrollLeft(200); // Sets the horizontal scroll position to 200px
            });
        });
    </script>
    <style>
        #scrollableDiv {
            width: 300px;
            height: 100px;
            overflow: auto;
            white-space: nowrap;
            border: 1px solid black;
        }
        .content {
            width: 800px;
            height: 100px;
        }
    </style>
</head>
<body>
<div id="scrollableDiv">
    <div class="content">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>
</div>
<br>
<button>Set Scroll Left to 200px</button>
</body>
</html>

執行程式後,向右滑動 div 內的內容並單擊下面的按鈕,它將把捲軸位置設定為 200 畫素。

jquery_ref_html.htm
廣告
© . All rights reserved.