← 中文资源

简体中文版本

getComputedStyle 读取生效样式

getComputedStyle 返回级联和单位解析后的生效值:2em 读出来是像素;内联 style 才是可写面,改动必须写回元素。

阅读英文原文

实现说明

演示用的数据放在这几个模块级绑定中:box、styles。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 每一步打印都带着自己的标签:font-size:、width px :、inline now:。

常见问题

「getComputedStyle 读取生效样式」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

核心语句

const box = document.createElement("div");
document.body.style.fontSize = "16px";
const styles = getComputedStyle(box);

代码示例

// resolved styles: getComputedStyle folds em/percent units into final pixel values
const box = document.createElement("div");
box.style.fontSize = "2em";
document.body.append(box);
document.body.style.fontSize = "16px";

const styles = getComputedStyle(box);
// "2em" 在 16px 根字号下解析为 32px
console.log("font-size:", styles.fontSize);

// percentage width resolves to pixels against the parent's content box
box.style.width = "50%";
console.log("width px :", getComputedStyle(box).width);

// computed 值是只读快照:改动必须写回元素的 .style
box.style.fontSize = "24px";
console.log("inline now:", box.style.fontSize);
console.log("computed :", getComputedStyle(box).fontSize);