1. 程式人生 > 其它 >offset獲取元素偏移,大小

offset獲取元素偏移,大小

offset翻譯過來就是偏移量,我們使用offset系列相關屬性可以動態的得到該元素的位置(偏移)、大小等。

●獲得元素距離帶有定位父元素的位置

●獲得元素自身的大小(寬度高度)

●注意:返回的數值都不帶單位

 

    <style>
      .father {
        width: 500px;
        height: 500px;
        background-color: aqua;
        position: absolute;
        left: 220px;
        top: 220px;
      }
      .son 
{ width: 150px; height: 150px; background-color: blueviolet; position: absolute; left: 200px; top: 150px; } </style> </head> <body> <div class="father"> <div class="son"></div> </div> </body
> <script> // offset 系列 var father = document.querySelector(".father"); var son = document.querySelector(".son"); // 可以得到元素的偏移 位置 返回的不帶單位的數值 console.log(father.offsetTop); console.log(father.offsetLeft); console.log(son.offsetLeft); // 可以獲得元素的寬高 console.log(son.offsetWidth); console.log(son.offsetHeight);
// 返回帶有定位的父親 否則返回的是body console.log(son.offsetParent); console.log(son.offsetNode); //返回父親最近一級的父親 親爸爸 不管父親有沒有定位 </script>