1. 程式人生 > >Jquery scrollTop() 和scrollLeft()使用

Jquery scrollTop() 和scrollLeft()使用

1》scrollTop() 方法設定或返回被選元素的【垂直滾動條位置】。當滾動條位置位於最頂部時,位置是0;

   語法: $(selector).scrollTop()、$(selector).scrollTop(position)    引數position : 規定以畫素為單位的垂直滾動條位置。

案例:

<body>
		<div style="border:1px solid black;width:100px;height:150px;overflow:auto">
			This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.
		</div><br>

		<button id="btn1">Get vertical position of the scrollbar</button>

		<button id="btn2">Set vertical position of the scrollbar</button>
		
		<p>Move the scrollbar down and click the button again.</p>
	</body>

</html>

<script src="js/jquery-3.3.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
	$(function(){
		  $("#btn1").click(function(){
		  	alert($('div').scrollTop());
		  });
		  
		  
		   $("#btn2").click(function(){
		   	//需要注意的是,這裡的數值不能加引號。也不用加px. 只需要給數值就可以了
		  	$('div').scrollTop(100)
		  })
	})
</script>

 

 

2》scrollLeft() 方法設定或返回被選元素的【水平滾動條位置】。當水平滾動條位置位於最左邊時,位置是0;

   語法: $(selector).scrollLeft()、$(selector).scrollLeft(position)    引數position : 規定以畫素為單位的垂直滾動條位置。

 

案例:

<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			.p1 {
				margin: 10px;
				padding: 5px;
				border: 2px solid #666;
				width: 800px;
				height: 500px;
			}
		</style>
	</head>

	<body>
		<div style="position:relative ;border:1px solid black;width:200px;height:100px;overflow:auto; ">
			<p class="p1">This is some textThis is some textThis is some textThis is some
				</p> 

		</div>

		<button id="btn1">Get vertical position of the scrollbar</button>

		<button id="btn2">Set vertical position of the scrollbar</button>

		<p>Move the scrollbar down and click the button again.</p>
	</body>

</html>

<script src="js/jquery-3.3.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
	$(function() {
		$("#btn1").click(function() {
			alert($('div').scrollLeft());
		});

		$("#btn2").click(function() {
			//需要注意的是,這裡的數值不能加引號。也不用加px. 只需要給數值就可以了
			$('div').scrollLeft(100)
		})
	})
</script>