offsetLeft和offsetTop获取元素偏移
offsetLeft和offsetTop获取元素偏移
offset翻译过来就是偏移量 我们使用offset系列相关属性可以动态的得到该元素的位置(偏移)、大小等
获得元素距离带有定位父元素的位置
获得元素自身的大小(宽度高度)
注意:返回的数值都不带单位!!!
(1)、如果没有父亲或者父亲有定位则以 body为准
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>offsetleft和offsettop的使用</title> <style> *{ margin: 0; padding: 0; } .test{ width: 300px; border: 5px solid black; margin: 10px; padding: 10px; /* 相对定位 */ position: relative; left: 100px; top: 320px; } </style> </head> <body> <div id="test" class="test"> <p>点击按钮获取 div 元素的左侧偏移量:</p> <p> <button onclick="myfn1()">点我</button> </p> <p> <span id="demo"></span> </p> </div> <h2>offsetLeft 是一个只读属性,返回当前元素相对于 offsetParent 节点左边界的偏移像素值。</h2> <h2>offsetLeft 和 offsetTop 理解为 当前元素 距离 父元素左上角的 偏移值(偏移量)</h2> <script> var testDiv = document.querySelector('#test'); var demo = document.querySelector('#demo'); // 获取 div 元素的左侧偏移量 // 获取div 元素的 顶部偏移量 function myfn1(){ demo.innerHTML = 'offsetLeft 为: '+testDiv.offsetLeft + ' | ' + 'offsetTop 为: ' + testDiv.offsetTop; } </script> </body> </html>
(2)、如果没有父亲或者父亲没有定位则以 body为准
例如:
<!DOCTYPE html> <html> <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: green; margin: 150px; border: 10px solid blue; } .son { width: 100px; height: 100px; background-color: lightblue; margin: 50px; } </style> </head> <body> <div> <div></div> </div> </body> <script> // dom对象---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>
