【发布时间】:2020-09-25 12:29:47
【问题描述】:
我想将使用getComputedStyle() 生成的所有计算样式添加到另一个按钮中。
我已经尝试过.cssText,但这里似乎需要做其他事情。
任何建议都可以做到这一点。
//获取样式并存入sessionstorage
const getStyle = getComputedStyle(document.getElementById("testButton"));
sessionStorage.setItem("getStylesItem", JSON.stringify(getStyle));
//将会话对象的样式设置为按钮
const jsonValue = JSON.parse(sessionStorage["getStylesItem"]);
const elem = document.getElementById('TestButton1');
elem.style.cssText = jsonValue.cssText;
//虚拟json值
{
alignContent: "normal",
alignItems: "center",
alignSelf: "auto",
alignmentBaseline: "auto",
all: "",
animation: "none 0s ease 0s 1 normal none running",
animationDelay: "0s",
animationDirection: "normal",
animationDuration: "0s",
animationFillMode: "none"
}
【问题讨论】:
-
jsonValue.cssText- 你的 JSON 值真的有这样的属性吗? (无法从您展示的简短示例中看出。) -
@04FS 感谢您抽出宝贵时间。所以我想将所有样式应用到另一个按钮中。这样做有什么技巧吗?
-
创建一个 css 类并将所有样式存储在其中。将 css 类名存储在 sessionStorage 中,并在您想在另一个按钮上重用时应用 css 类。
-
你将不得不遍历你到达那里的对象。您可以尝试组装一个可以分配给
cssText的字符串 - 但是您可能必须撤消 camelCasing (我认为分配给 cssText 不会起作用。)直接分配它们中的每一个可能更有意义的是,这适用于 camelCase 属性名称。 -
如果我将每个属性都应用到我的 json 中,那么它将被硬编码。所以想按原样申请,这样它会更强大或更未来。
标签: javascript css