scrollLeft()方法獲取或設(shè)置所選元素的水平滾動(dòng)條位置。
當(dāng)使用scrollLeft()方法獲取位置時(shí),它將返回第一個(gè)選定元素的滾動(dòng)條的水平位置。
當(dāng)使用scrollLeft()方法設(shè)置位置時(shí),它將為所有選定元素設(shè)置滾動(dòng)條的水平位置。
獲取水平滾動(dòng)條位置:
$(selector).scrollLeft()
設(shè)置水平滾動(dòng)條位置:
$(selector).scrollLeft(value)
獲取DIV的scrollLeft:
$("div").scroll(function(){
$(this).scrollLeft();
});測試看看?/?設(shè)置DIV的scrollLeft:
$("button").click(function(){
$("div").scrollLeft(150);
});測試看看?/?設(shè)置文檔的scrollLeft:
$("button").click(function(){
$(document).scrollLeft(300);
});測試看看?/?用戶滾動(dòng)頁面時(shí)添加平滑滾動(dòng):
let size = $(".main").outerWidth(); // 獲取".main" 寬度
$(window).keydown(function(event) {
if(event.which === 39) { // 如果按下向右箭頭鍵
$("html, body").animate({scrollLeft: "+=" + size}, 250);
} else if(event.which === 37) { // 如果按向左箭頭鍵
$("html, body").animate({scrollLeft: "-=" + size}, 250);
}
});測試看看?/?| 參數(shù) | 描述 |
|---|---|
| value | 一個(gè)整數(shù),指示將滾動(dòng)條設(shè)置為的新位置 |