元素JSDOM 样式读取最佳实践

Best practice for reading styles of element JSDOM

要使用 JSDOM 从元素获取样式属性,我使用以下方法:

window.getComputedStyle(element)

这是我找到的唯一示例。使用 element.style.someAttribute 似乎没有 return 任何东西。

使用 getComputedStyle 是查找属性值的最佳方法吗?

好吧!

element.style 仅反映 HTML 元素的 style 属性的内容。不考虑真实样式可以设置class样式,id样式等

看这里:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style (强调我的)

The HTMLElement.style property is used to get as well as set the inline style of an element. When getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute.

这意味着:

mySpan = document.getElementById('my-span')
console.info('element.style')
console.info('color', mySpan.style.color)
console.info('font-weight', mySpan.style.fontWeight)
console.info('getComputedStyle')
console.info('color', window.getComputedStyle(mySpan).color)
console.info('font-weight', window.getComputedStyle(mySpan).fontWeight)
#my-span {
  font-weight: bold;
}
<span id="my-span" style="color: red;">This is red and bold</span>