首页 > 解决方案 > 是否可以“getComputedStyle”不在浏览器 DOM 中的元素?

问题描述

我无法找到有关是否可以getComputedStyle使用不在浏览器 DOM 中的元素的信息。

我的测试表明未插入浏览器 DOM 的元素不会获得计算样式。

var el = document.createElement("span")
el.id = "greeting"
el.textContent = "Hi there"
el.setAttribute("style", "background-color: yellow;")

console.log("Element in JS memory:", window.getComputedStyle(el).backgroundColor)

document.querySelector("body").appendChild(el)

console.log("Element in browser dom:", window.getComputedStyle(document.querySelector("#greeting")).backgroundColor)

但是,让浏览器为 JavaScript 内存中的文档或元素计算样式是可能的,这并没有让我觉得不合理。或者可能有一些包可以做到这一点。但我还没有找到。

这可能吗(无需自己编写复杂的 css 计算逻辑)?

标签: javascripthtmlcssgetcomputedstyle

解决方案


推荐阅读