當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


JQuery scrollLeft()用法及代碼示例


scrollLeft()方法是jQuery中的內置方法,用於返回或設置滾動條的水平位置。

用法:

$(selector).scrollLeft(position)

參數:此方法接受可選的單個參數位置。用於指定水平滾動條的位置(以像素為單位)。


返回值:此方法返回滾動條的位置。

下麵的示例說明了jQuery中的scrollLeft()方法。

示例1:

<!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> 
        <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> 
       
    </body> 
   
</html>

輸出:
在單擊按鈕之前:

箭頭所示的返回位置:

示例2:

<!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> 
        <div style=""> 
            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> 
    </body> 
</html>

輸出:
在點擊箭頭所示的按鈕位置之前。

單擊箭頭所示的按鈕位置後。



相關用法


注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery | scrollLeft() with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。