如何获得JavaScript中HTML元素的最终的,最终的,继承的样式值?我已经知道 element.style
仅获取内联样式,并且 getComputedStyle()
仅对内联样式进行基本转换(它似乎没有从样式表继承任何内容)。如何获得继承的样式值?
我不想使用jQuery(因为我知道有可能使用纯JavaScript解决方案,尽管我的应用程序中已经使用了jQuery)。我不知道样式表的配置是什么提前,因为这些表是与SASS一起编译的。
我的具体情况是,我试图从样式表中获取基于 Canvas 的绘图任务的业务定义颜色,并且颜色在CSS中定义。我目前正在尝试使用类似以下的代码来提取我的实体。
var testElement = document.createElement("span");
var entity_type_color_table = {};
function getEntityTypeColor(entity_type) {
if (!entity_type_color_table[entity_type]) {
testElement.className = entity_type + "-color";
entity_type_color_table[entity_type] =
document.defaultView.getComputedStyle(testElement, null)
.getPropertyValue("color");
}
return entity_type_color_table[entity_type];
}
最佳答案
您没有看到任何样式表样式,因为尚未将测试元素附加到文档。创建testElement
后,请执行以下操作:
document.body.appendChild(testElement);
应该足够了。
另外,如果将测试元素永久连接是一个问题,则可以在测试功能中附加和分离它:
if (!entity_type_color_table[entity_type]) {
testElement.className = entity_type + "-color";
document.body.appendChild(testElement);
entity_type_color_table[entity_type] =
document.defaultView.getComputedStyle(testElement, null)
.getPropertyValue("color");
testElement.remove();
}