我使用rems 作為我的 CSS 大小,也在getBoundingClientRectjavascript 中使用。默認情況下getBoundingClientRect回傳它的值px。是否有可能讓它回傳rems 中的值?它會使我的代碼更簡單一些。
uj5u.com熱心網友回復:
您必須通過將像素除以檔案的計算字體大小來轉換它:
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375220.html
標籤:javascript css dom
