今天發現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