offsetTop与offsetLeft的真实距离

46 阅读1分钟

记录下这两个属性的用法

offsetTop:是一个只读属性,返回当前元素相对于 offsetParent 节点顶部边界的偏移像素值

offsetLeft:是一个只读属性,返回当前元素相对于 offsetParent 节点左边界的偏移像素值

offsetParent:距离元素最近的一个具有定位的祖宗元素(relative,absolute,fixed),若祖宗都不符合条件,offsetParent为body

图解

未命名文件(1).png

试一下


  <!DOCTYPE html>

   <html>

   <head>

   <meta charset="utf-8" />

       <title>元素大小</title>

   <style>

       body {

       margin: 0;

       }




       .title-text {

       color: rgb(51, 51, 51);

       font-size: 18px;

       background-color: rgb(255, 255, 255);

       }

       .wrap {

       background: #abcdef;

       width: 200px;

       height: 200px;

       }

       .wrap .inner-wrap {

       background: pink;

       width: 100px;

       height: 100px;

       }

       .wrap-position {

       position: relative;

       background: #abcdef;

       width: 200px;

       height: 200px;

       }




       .wrap-position .inner-wrap {

       background: pink;

       width: 100px;

       height: 100px;

       }







       .wrap-outer {

       position: relative;

       background: #abcdef;

       padding-top: 10px;

       width: 300px;

       height: 300px;

       border: 1px solid green;

       }




       .wrap-outer .wrap-one {

       background: #abcdef;

       width: 200px;

       height: 200px;

       border: 1px solid yellow;

       }


       .wrap-outer .inner-wrap {

       background: pink;

       width: 100px;

       height: 100px;

       }

   </style>

   </head>

   <body>

   <br class="title-text">

   <div class="wrap">

   <div class="inner-wrap" id="inner-wrap" onclick="offsetTopTest('inner-wrap')">点击获取子元素offsetTop</div>

   parent-position:static

   </div>




   <br class="title-text">




   <div class="wrap-position">

   <div class="inner-wrap" id="inner-wrap1" onclick="offsetTopTest('inner-wrap1')">点击获取子元素offsetTop</div>

   parent-position:relative

   </div>




   <br class="title-text">




   <div class="wrap-outer">

   <div class="wrap-one">

   <div class="inner-wrap" id="inner-wrap2" onclick="offsetTopTest('inner-wrap2')">点击获取子元素offsetTop</div>

   parent-position:static

   </div>

   parent-position:relative

   </div>

   <script type="text/javascript">

   function offsetTopTest(id) {

   const divDom = document.getElementById(id)

   console.log('divDom.offsetTop=', divDom.offsetTop);

   }

   </script>

   </body>




   </html>

end

感谢网友的文章:www.jb51.net/article/219…