jQuery的offset和position方法

获取/设置标签的的位置数据
offset()用于读取和设置offset值,相对于页面左上角的坐标(有left和top值)
position():相对于父元素左上角的位置(有left和top值)
代码示例如下

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>jquery的offset和position方法</title>
		<style type="text/css">
			*{
				margin:0;
				padding: 0;
			}
			#box1{
				width: 300px;
				top: 30px;
				height: 300px;
				background-color: #ADFF2F;
				position: absolute;
			}
			#box2{
				width: 200px;
				height: 200px;
				top: 50px;
				background-color: azure;
				position: absolute;
			}
		</style>
		<script type="text/javascript" src="../js/jquery-3.1.1/jquery-3.1.1.min.js" ></script>
		<script type="text/javascript">
			$(function(){
				$("#btn4").click(function(){
					var $box1 = $("#box1").offset();
//					alert($box1);
				console.log($box1.left,$box1.top);
				var $box2 = $("#box2").offset();
				console.log($box2.left,$box2.top);
				var $b1 = $("#box1").position();
				console.log($b1.left,$b1.top);
				var $b2 = $("#box2").position();
				console.log($b2.left,$b2.top);
				});
				$("#btn5").click(function(){
					$("#box1").offset({
						left:10,
						top:50
					});
				});
			});
		</script>
	</head>
	<body>
		<div id="box1">
			<div id="box2"></div>
		</div>
		<button id="btn4">读取position和offset值</button>
		<button id="btn5">设置offset值</button>
	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值