使用Javascript的style.fontWeight.value获取CSS font-weight值返回undefined
错误原因
HTMLElement.style返回的CSSStyleDeclaration对象中,fontWeight本身就是直接返回属性值的字符串类型字段,不是包含value属性的对象,你额外追加.value访问了不存在的属性,所以返回undefined。
修复方案
直接去掉末尾的.value即可,修改后的JavaScript代码如下:
document.getElementById("results").innerText = document.getElementById("getfontweightfrom").style.fontWeight;
修改后运行即可正确拿到内联样式中定义的"900"值,该写法同时兼容bold这类文本关键词取值的读取场景。
拓展说明
- 如果你要读取的font-weight不是定义在元素的内联style属性中,而是来自外部样式表、内部style标签的样式,使用
style.fontWeight无法读取到对应值,此时可以用计算样式API获取最终生效值:
const elem = document.getElementById("getfontweightfrom"); const computedStyle = window.getComputedStyle(elem); document.getElementById("results").innerText = computedStyle.fontWeight;
内容的提问来源于stack exchange,提问作者Glen Keybit
相关产品推荐
相关产品推荐

