回答jquery怎么设置元素的位置

 所属分类:web前端开发

 浏览:99次-  评论: 0次-  更新时间:2022-11-02
描述:更多教程资料进入php教程获得。 设置方法:1、用offset()设置元素相对于文档的偏移坐标,语法“元素对象.offset({top:偏移值,left:偏移值})...
更多教程资料进入php教程获得。

设置方法:1、用offset()设置元素相对于文档的偏移坐标,语法“元素对象.offset({top:偏移值,left:偏移值})”;2、用scrollTop()设置元素垂直滚动条位置;3、用scrollLeft()设置元素水平滚动条位置。

前端(vue)入门到精通课程:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本教程操作环境: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>
登录后复制

1.gif

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>
登录后复制

2.gif

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>
登录后复制

3.gif

【推荐学习:jQuery视频教程、web前端视频】

以上就是jquery怎么设置元素的位置的详细内容,更多请关注zzsucai.com其它相关文章!

 标签: jquery,
积分说明:注册即送10金币,每日签到可获得更多金币,成为VIP会员可免金币下载! 充值积分充值会员更多说明»

讨论这个素材(0)回答他人问题或分享使用心得奖励金币

〒_〒 居然一个评论都没有……

表情  文明上网,理性发言!