登录  /  注册

jquery怎么设置元素的位置

青灯夜游
发布: 2022-05-26 14:25:37
原创
2236人浏览过

设置方法: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>
登录后复制

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怎么设置元素的位置的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号