鍍金池/ 問答/HTML/ 原生js獲取距離頁面頂端的距離

原生js獲取距離頁面頂端的距離

不用jquery的情況下,因?yàn)橛玫氖莢ue框架,獲取元素到頁面頂端的距離
demo的代碼如下:
問題1 offsetTop只能獲取到有定位元素父級(jí)的距離,怎么獲取到頁面頂端距離呢
問題2 子級(jí)有了transform 24px但offsetTop卻獲取不到 下面打印出來的值是0
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"

    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>dddddddddddddd</p>
<div class="box">

  <div class="child">
  </div>

</div>
</body>
<style>
p{

 line-height:29px;
font-size:29px}

.box{

 width:100px;
height:100px;
margin-top: 120px;
margin-left:180px;
border:2px solid green;
position: relative;}

.child{

width:50px;
height:50px;
transform: translateY(24px);
border:1px solid red; }

</style>
<script>
var Child=document.getElementsByClassName('child')[0]
var Box=document.getElementsByClassName('box')[0]
console.log(Child.offsetTop) // 得到0
console.log(Box.offsetTop); //178
// console.log(Box.offsetLeft)
// offsetTop //有定位元素的父級(jí)距離
</script>
</html>

回答
編輯回答
局外人
問題1 offsetTop只能獲取到有定位元素父級(jí)的距離,怎么獲取到頁面頂端距離呢

getBoundingClientRect().top

問題2 子級(jí)有了transform 24px但offsetTop卻獲取不到 下面打印出來的值是0

見問題1回答;

clipboard.png

對(duì)么?

2017年6月30日 18:40