我使用 rem
作为我的 CSS 大小,并且还在 javascript 中使用 getBoundingClientRect
。 getBoundingClientRect
默认以 px
返回它的值。是否有可能让它返回 rem
中的值?这将使我的代码更简单一些。
最佳答案
您必须通过将像素除以文档的计算字体大小来转换它:
function convertPixelsToRem(px) {
return px / parseFloat(getComputedStyle(document.documentElement).fontSize.replace('px', ''));
}
console.log(convertPixelsToRem(div.getBoundingClientRect().width))
#div{
width:100px;
height:100px;
background-color:grey;
margin-bottom:10px;
}
#div2{
width:6.25rem;
height:100px;
background-color:grey;
}
<div id="div"></div>
<div id="div2"></div>
关于javascript - `getBoundingClientRect` 可以返回 `rem` 中的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70193305/