用 getComputedStyle 只能取得转化成px的值
先说思路,得到需要计算属性的px值,然后再得到html标签里的font-size的px值,因为rem是基于html的font-size来的。1rem就是一个font-size的px值。
献上代码:css
*{
margin: 0;
padding: 0;
}
html{
font-size: 20px;
}
#box{
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");
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答5.1k 阅读✓ 已解决
5 回答1.9k 阅读
取到的是浏览器默认单位,你进行一下换算呗
px/16 = rem