1.1.1 offset 概述
offset 翻译过来就是偏移量, 我们使用 offset系列相关属性可以动态的得到该元素的位置(偏移)、大小等。
1. 获得元素距离带有定位父元素的位置 2. 获得元素自身的大小(宽度高度) 3. 注意:返回的数值都不带单位 4. offsetLeft:它以带有定位的父亲为准,如果没有父亲或者父亲没有定位,则以 body 为准
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } .father { /* position: relative; */ width: 200px; height: 200px; background-color: pink; margin: 150px; } .son { width: 100px; height: 100px; background-color: purple; margin-left: 45px; } .w { height: 200px; background-color: skyblue; margin: 0 auto 200px; padding: 10px; border: 15px solid red; } </style> </head> <body> <div class="father"> <div class="son"></div> </div> <div class="w"></div> <script> // offset 系列 var father = document.querySelector('.father'); var son = document.querySelector('.son'); // 1.可以得到元素的偏移 位置 返回的不带单位的数值 console.log(father.offsetTop); // 150 console.log(father.offsetLeft); // 150 // 它以带有定位的父亲为准 如果么有父亲或者父亲没有定位 则以 body 为准 console.log(son.offsetLeft); // 195。如果父元素定位了,则输出45 var w = document.querySelector('.w'); // 2.可以得到元素的大小 宽度和高度 是包含padding + border + width 【即使设为box-sizing: border-box,也包含边框、内边距】 console.log(w.offsetWidth); // 1263 console.log(w.offsetHeight); // 250 // 3. 返回带有定位的父亲 否则返回的是body console.log(son.offsetParent); // 返回带有定位的父亲 否则返回的是body console.log(son.parentNode); // 返回父亲father 是最近一级的父亲 亲爸爸 不管父亲有没有定位 </script> </body> </html>
1.1.2 offset 与 style 区别
offset
-
offset 可以得到任意样式表中的样式值
-
offset 系列获得的数值是没有单位的
-
offsetWidth 包含padding+border+width
-
offsetWidth 等属性是只读属性,只能获取不能赋值
-
所以,我们想要获取元素大小位置,用offset更合适
style
-
style 只能得到行内样式表中的样式值
-
style.width 获得的是带有单位的字符串
-
style.width 获得不包含padding和border 的值
-
style.width 是可读写属性,可以获取也可以赋值
-
所以,我们想要给元素更改值,则需要用style改变
因为平时我们都是给元素注册触摸事件,所以重点记住 targetTocuhes
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .box { width: 200px; height: 200px; background-color: pink; padding: 10px; } </style> </head> <body> <div class="box" style="width: 200px;"></div> <script> // offset与style的区别 var box = document.querySelector('.box'); console.log(box.offsetWidth); // 220 console.log(box.style.width); // 200px // box.offsetWidth = '300px'; // 无效 box.style.width = '300px'; </script> </body> </html>