读取元素JSDOM样式的最佳实践[关闭]

问题描述 投票:-2回答:1

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

window.getComputedStyle(element)

这是我发现的唯一例子。使用element.style.someAttribute似乎没有返回任何东西。

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

公司!

javascript html testing jsdom
1个回答
1
投票

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

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

HTMLElement.style属性用于获取和设置元素的内联样式。获取时,它返回一个CSSStyleDeclaration对象,该对象包含该元素的所有样式属性的列表,其中的值是为元素的内联样式属性中定义的属性指定的。

这意味着:

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>
© www.soinside.com 2019 - 2024. All rights reserved.