为何getBoundingClientRect().bottom与getComputedStyle().bottom返回值不同?
为什么
ball.getBoundingClientRect().bottom和parseInt(getComputedStyle(ball).bottom)返回值不一致? 你疑惑的是在以下代码场景中,两个API的返回值为何不相等,原本预期数值相同:
HTML代码
<div class="ball"></div>
CSS代码
.ball { height : 5rem; width : 5rem; background-color : salmon; border-radius : 50%; position : relative; top : 40vh; left : 45vw; }
JavaScript代码
console.log( ball.getBoundingClientRect().bottom ); console.log( parseInt(getComputedStyle(ball).bottom) );
核心原因:两个API的计算逻辑完全不同
getBoundingClientRect().bottom:返回元素底部边缘到浏览器视口顶部的绝对像素距离。计算逻辑是「视口顶部到元素顶部的距离 + 元素自身高度」,和元素的CSS定位属性无关,只看元素在视口中的实际位置。getComputedStyle(ball).bottom:返回元素CSS定位的计算值。因为你只给元素设置了top:40vh,没有显式定义bottom属性,浏览器会自动将bottom计算为auto。而parseInt("auto")会返回NaN,这就是数值不一致的直接原因。
额外说明
就算你给元素显式设置bottom属性,或者把定位改成absolute/fixed(需给父容器设置定位),这两个值也不会相等:
getComputedStyle的bottom代表元素底部相对于定位父容器底部的距离,参考系是父容器;getBoundingClientRect().bottom的参考系始终是浏览器视口,两者的计算基准完全不同。
内容的提问来源于stack exchange,提问作者Anoop Lamba
相关产品推荐
相关产品推荐

