Js gets the remvalue set in css

you can only get the value converted to px with getComputedStyle

Mar.06,2021

get the default unit of the browser. You can convert it

.

px/16 = rem


talk about the idea first, get the PX value of the attribute that needs to be calculated, and then get the PX value of font-size in the html tag, because rem is based on html's font-size. 1rem is the PX value of a font-size.
present the code: css

*{
    margin: 0;
    padding: 0;
}
html{
    font-size: 20px;
}
-sharpbox{
    width: 9rem;
    height: 9rem;
    background-color: red;
}

html

<div id="box"></div>

js

var box = document.getElementById("box");
var boxStyle = window.getComputedStyle(box).width.slice(0,-2);

var html = document.getElementsByTagName("html");
var htmlStyle = window.getComputedStyle(html[0]).fontSize.slice(0,-2);
console.log(boxStyle/htmlStyle + "rem");
Menu