今天发现getBoundingClientRect()
这个方法可以返回元素的大小及其相对于视口的位置,对于获取元素到顶部距离省事很多。
当然jq也有获取元素到顶部的距离的方法。写个例子测试一下,顺便看看变化。
示例代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <style> body{padding: 0;margin: 0;} .ban{width: 500px;height: 200px;background: lightblue;margin: 0 0 0 200px;} .box-wp{width: 500px;position: relative;padding-top: 40px;background: orange;margin: 0 0 0 200px;} .box{width: 200px;height: 200px;background: green;position: relative;margin: 0 0 0 200px;} label{position: absolute;} </style> <body> <div class="ban">box1:高度200px</div> <div class="box-wp"> <label for="">box2:padding-top值40</label> <div class="box">box3</div> </div> <script src="js/jquery.min.js"></script> <script> window.addEventListener('load',function(){ var box = document.querySelector('.box'); var rec = box.getBoundingClientRect(); var pos = $(box).position().top; var offset = $(box).offset().top; console.log('offsetTop:'+box.offsetTop); console.log('getBoundingClientRect:'+parseInt(rec.top+document.documentElement.scrollTop)) console.log('position:'+pos); console.log('offset'+offset) }) </script> </body> </html>
在测试的过程中发现,当页面滚动的时候,不加上滚动距离是不准确的。js中offsetTop仅获取元素最近的父元素的距离,当这个父元素有相对定位的时候。
同理,jq中的position().top也是。
例子下载地址:
https://blog-static.cnblogs.com/files/cyppi/getBoundingClientRect.rar
关于getBoundingClientRect的更多解析:
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect