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

HTML

1
2
3
4
5
6
<input type="button" name="" id="" value="点击运动" />
<div id="div1">
    <div id="div2">
        <div id="div3"></div>
    </div>
</div>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
    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.onclick=function(){
    oDiv3.style.left=-(oDiv3.getBoundingClientRect().left-parseInt(oDiv3.offsetLeft))+"px";
}

  

posted @   carol72  阅读(4214)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示