【发布时间】:2022-01-08 13:57:43
【问题描述】:
我使用rems 作为我的CSS 尺寸,并且还在javascript 中使用getBoundingClientRect。 getBoundingClientRect 默认返回 px 中的值。是否有可能让它返回rems 中的值?它会让我的代码更简单一些。
【问题讨论】:
标签: javascript css dom
我使用rems 作为我的CSS 尺寸,并且还在javascript 中使用getBoundingClientRect。 getBoundingClientRect 默认返回 px 中的值。是否有可能让它返回rems 中的值?它会让我的代码更简单一些。
【问题讨论】:
标签: javascript css dom
您必须通过将像素除以文档的计算字体大小来转换它:
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>
【讨论】: