首頁 > web前端 > 前端問答 > jquery怎麼設定元素的位置

jquery怎麼設定元素的位置

青灯夜游
發布: 2022-05-26 14:25:37
原創
2559 人瀏覽過

設定方法:1、用offset()設定元素相對於文件的偏移座標,語法「元素物件.offset({top:偏移值,left:偏移值})」;2、用scrollTop()設定元素垂直捲軸位置;3、用scrollLeft()設定元素水平捲軸位置。

jquery怎麼設定元素的位置

本教學操作環境:windows7系統、jquery1.10.2版本、Dell G3電腦。

jquery設定元素位置的多種方法

#1、使用offset()

offset() 方法可設定被選元素相對於文件的偏移座標。

$(selector).offset({top:value,left:value})
登入後複製
  • 規定以像素為單位的 top 和 left 座標。

範例:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="js/jquery-1.10.2.min.js"></script>
		<style>
			p {
				width:150px;
				background-color:pink;
				padding: 5px;
			}
		</style>
		<script>
			$(document).ready(function() {
				$("button").click(function() {
					$("p").offset({
						top: 200,
						left: 200
					});
				});
			});
		</script>
	</head>
	<body>

		<p>这是一个段落。</p>
		<button>设置P元素的偏移坐标</button>

	</body>
</html>
登入後複製

jquery怎麼設定元素的位置

#2、使用scrollTop()

scrollTop( ) 方法可設定被選元素的垂直捲軸位置。

$(selector).scrollTop(position)
登入後複製

提示:當捲軸位於最頂部時,位置是 0。

範例:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").click(function() {
					$("div").scrollTop(100);
				});
			});
		</script>
	</head>
	<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>垂直滚动条的位置设置为100px</button>

	</body>
</html>
登入後複製

jquery怎麼設定元素的位置

#3、使用使用scrollLeft()

scrollLeft() 可以設定匹配元素相對捲軸左側的偏移,即水平捲軸的位置。

$(selector).scrollLeft(position)
登入後複製

捲軸的水平位置指的是從其左側捲動過的像素數。當捲軸位於最左側時,位置是 0。

範例:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(document).ready(function() {
				$("button").click(function() {
					$("div").scrollLeft(100);
				});
			});
		</script>
	</head>
	<body>

		<div style="border:1px solid black;width:100px;height:130px;overflow:auto">
			The longest word in the english dictionary is: pneumonoultramicroscopicsilicovolcanoconiosis.
		</div><br>
		<button>水平滚动条的位置设置为100 px</button>

	</body>
</html>
登入後複製

jquery怎麼設定元素的位置

【推薦學習:jQuery影片教學web前端影片

以上是jquery怎麼設定元素的位置的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
引入jQuery 文件
來自於 1970-01-01 08:00:00
0
0
0
jquery筆記哪裡有下?
來自於 1970-01-01 08:00:00
0
0
0
javascript - vue+webpack怎麼引入jquery
來自於 1970-01-01 08:00:00
0
0
0
php+jquery的問題
來自於 1970-01-01 08:00:00
0
0
0
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板