【问题标题】:Can `getBoundingClientRect` return values in `rem`?`getBoundingClientRect` 可以在`​​rem` 中返回值吗?
【发布时间】:2022-01-08 13:57:43
【问题描述】:

我使用rems 作为我的CSS 尺寸,并且还在javascript 中使用getBoundingClientRectgetBoundingClientRect 默认返回 px 中的值。是否有可能让它返回rems 中的值?它会让我的代码更简单一些。

【问题讨论】:

    标签: javascript css dom


    【解决方案1】:

    您必须通过将像素除以文档的计算字体大小来转换它:

    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>

    【讨论】:

    • 谢谢。我就是这么想的。
    猜你喜欢
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 2021-03-21
    • 2013-08-14
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多