【问题标题】:Javascript: How to set css style generated from getComputedStyles() into a buttonJavascript:如何将 getComputedStyle() 生成的 CSS 样式设置为按钮
【发布时间】: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


【解决方案1】:

循环 CSS 对象,然后形成一个字符串。您应该使用 cssText 的内联样式。

const jsonValue = JSON.parse(sessionStorage["getStylesItem"]);
const elem = document.getElementById('TestButton1');

let cssText = '';
for (const property in jsonValue) {
  if (!Number.isNaN(parseInt(property))) continue;
  cssText += `${property}:${jsonValue[property]}`;
}

elem.style.cssText = cssText;

CSSStyleDeclaration 对象具有像 0: "align-content", 1: "align-items" 这样的数字属性,因此您只需过滤非数字属性。

【讨论】:

  • 您好,感谢您的宝贵时间。收到 Uncaught ReferenceError 错误:未定义样式
  • 是样式[属性] 吗?或样式[属性]
  • 啊,我的错。应该是jsonValue[property]
  • 那是完美的。我会做一些调整。谢谢你的时间。
  • 不客气。您可以过滤现有属性,使其变得简单。
【解决方案2】:

这也可以通过使用for loop 来实现。

//用于设置视野存储

const button = document.getElementById("test");
if (button) {
  const getStyle = getComputedStyle(button);
  let testStyle = {};
  for (const key in getStyle) {
    testStyle[key] = getStyle[key];
  }
  sessionStorage.setItem("testStyles", JSON.stringify(testStyle));
}

//用于获取值并应用于您的按钮

  const elem = document.getElementById('button1');
  const getParam = sessionStorage(JSON.parse["testStyles"]);
  if (elem && getParam) {
    const elemStyle = elem.style;
    if (elemStyle) {
      for (const key in getParam) {
        elemStyle[key] = getParam[key];
      }
    }
  }

【讨论】:

  • 不错的解决方案。
猜你喜欢
  • 2012-08-24
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
相关资源
最近更新 更多