1. 程式人生 > 其它 >offsetLeft和offsetTop獲取元素偏移

offsetLeft和offsetTop獲取元素偏移

 offset概述

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

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

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

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

 

  程式碼示例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; } .father { width: 200px; height: 200px; background-color: pink; margin: 150px
; } .son { width: 100px; height: 100px; background-color: purple; margin: 45px; } </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); // 它以帶有定位的父親為準﹑如果麼有父親或者父親沒有定位則以 body為準 console.log(son.offsetLeft); // 可以得到元素的大小 寬度和高度 </script> </html>