1、offset
(1)概述
offset就是偏移量,使用offset的相關屬性可以動態地得到該元素的位置、大小等
- 獲取元素距離父元素(父元素要有定位)的位置
- 獲得元素的自身大小
- 返回數值不帶單位
2、獲取位置
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>test</title> <style type="text/css"> .test{ height: 100px; width: 200px; background-color: black; position: relative; top:100px; left: 200px; } .big{ height: 400px; width: 400px; background-color: #ffffcc; margin: 0 auto; position: absolute; top: 100px; left: 100px; } </style> </head> <body> <div class="big"> <div class="test"></div> </div> <script> var father=document.querySelector(".big"); var son=document.querySelector(".test"); console.log(father.offsetTop); console.log(son.offsetLeft); </script> </body> </html>
子元素以帶有定位的父元素為准,如果沒有父元素或者父元素沒有定位則以body為准
3、獲取元素的大小
<body> <div class="big"> <div class="test"></div> </div> <script> var father=document.querySelector(".big"); var son=document.querySelector(".test"); console.log(father.offsetHeight); console.log(son.offsetWidth); </script> </body>
在計算元素的大小的時候是包含padding和border的
可以動態獲取盒子的大小,瀏覽器
4、獲取父元素
(1)offsetParent
<body> <div class="big"> <div class="test"></div> </div> <script> var father=document.querySelector(".big"); var son=document.querySelector(".test"); console.log(son.offsetParent); </script> </body>
返回父元素,父元素沒有定位的話返回body
(2)parentNode
<body> <div class="big"> <div class="test"></div> </div> <script> var father=document.querySelector(".big"); var son=document.querySelector(".test"); console.log(son.parentNode); </script> </body>
返回的也是父元素,不管父元素有沒有定位,都會返回
5、offset與style
(1)offset
- offset 可以得到任意樣式表中的樣式值
- offset 系列獲得的數值是沒有單位的
- offsetWidth 包含padding+ border + width
- offsetWidth 等屬性是只讀屬性,只能獲取不能賦值
- 我們想要獲取元素大小位置,用offset更合適
(2)style
- style 只能得到行內桃式表中的樣式值
- style.width 獲得的是帶有單位的字符串
- style.width 獲得不包含padding和border的值
- style.width是可讀寫屬性,可以獲取也可以賦值
- 我們想要給元素更改值,則需要用style改變
6、獲取鼠標的坐標
<body> <div class="box"></div> <script> var father=document.querySelector(".box"); father.addEventListener("click",function(e){ var x=e.pageX-this.offsetLeft; var y=e.pageY-this.offsetTop; this.innerHTML="x:"+x+"y:"+y; }) </script> </body>
鼠標在瀏覽器內的位置減去盒子舉例瀏覽器的舉例,即為鼠標在盒子內的位置