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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。