DOM-获得元素定位父级及距离

HTML

<input type="button" name="" id="" value="点击运动" />
<div id="div1">
	<div id="div2">
		<div id="div3"></div>
	</div>
</div>

CSS

#div1,#div1 div{
	position: absolute;
	top: 10px;
}
#div1{
	width: 100px;
	height: 100px;
	background: red;
	left: 100px;
	border: 2px solid #000;
	top: 100px;
}
#div2{
	width: 60px;
	height: 60px;
	background: blue;
	left: 30px;
	border: 2px solid #fff;
}
#div3{
	width: 30px;
	height: 30px;
	background: yellow;
	left: 20px;
	border: 2px solid orange;
	transition: 1s left;
}

JS

/*
 	DOM节点
 * node.offsetParent最近的有定位属性的祖先节点
 * 		如果祖先节点都没有定位,那么默认为body
 * 
 * node.offsetLeft/node.offsetTop 最近的有定位属性的祖先节点的距离
 * 
 * node.offsetLeft左外边框到定位父级的左内边框的距离
 * node.offsetTop上外边框到定位父级的上内边框的距离
 * 
 * 
 * node.getBoundingClientRect()
 * node.getBoundingClientRect().left
 * 	获取元素的盒模型信息
 * 	返回值为一个对象
 * 		left top bottom right width height 
 * 		相对于浏览器可视区域
 * 		注意:获取的值会根据滚动条滚动的距离变换的
 * 		
 * 
 *
 * 
 * */

//点击按钮,div3运动到窗口边上
var oBtn=document.getElementsByTagName("input")[0];
var oDiv3=document.getElementById("div3");
oBtn.οnclick=function(){
	oDiv3.style.left=-(oDiv3.getBoundingClientRect().left-parseInt(oDiv3.offsetLeft))+"px";
}

  

转载于:https://www.cnblogs.com/yangxue72/p/8006562.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值