繁体   English   中英

Javascript getComputedStyle - 复制 object 没有参考

[英]Javascript getComputedStyle - copy object without reference

我想更改输入字段边框的颜色。 但在更改之前,我需要通过 getComputedStyle 保存初始 CSS 以便我可以将输入字段的所有初始 CSS 设置回来。 问题是getComputedStyle的object不是固定的,是动态变化的。

我试图在没有参考的情况下将 object 复制到一个新的中,但是我无法使用属性 getPropertyValue,因为它是 object 的不同类型。 有什么办法可以找回输入字段的初始 CSS 吗?

我的代码如下:

 const input_element = document.getElementById('text-id'); let computedStyle_fixed; function change_color() { // get computed style const computedStyle = window.getComputedStyle(input_element); // copy computed style into new object without reference computedStyle_fixed = JSON.parse(JSON.stringify(computedStyle)); // change the border color of the input field input_element.style.borderColor = 'red'; } function retrieve_color() { Array.from(computedStyle_fixed).forEach( key => element.style.setProperty(key, computedStyle_fixed.getPropertyValue(key), 'important') ) }
 <input type='text' id='text-id'> <button onclick='change_color()'>Change color</button> <button onclick='retrieve_color()'>Retrieve color</button>

您的代码中存在许多问题。 首先在这一行:

const computedStyle = window.getComputedStyle(input_element);

window.getComputedStyle返回一个CSSStyleDeclaration object 复制时使用:

computedStyle_fixed = JSON.parse(JSON.stringify(computedStyle));

分配给computedStyle_fixed的 object 是普通的 object,而不是CSSStyleDeclaration object。 这会在检索颜色 function 中进一步解释。

然后在:

Array.from(computedStyle_fixed)

Array.from期望参数是一个数组,如具有长度属性的 object 或可迭代的 object。 computedStyle_fixed两者都不是,因此结果是一个空数组,并且下面的forEach什么都不做(因为长度为 0)。

forEach回调中,有:

computedStyle_fixed.getPropertyValue(key)

computedStyle_fixed object 没有getPropertyValue方法(见上文),因此如果执行该行,结果将是类型错误。

要迭代computedStyle_fixed object 的属性,请使用Object.keys并使用方括号表示法访问属性,而不是(缺少) getPropertyValue方法,例如

Object.keys(computedStyle_fixed).forEach(key => 
   element.style.setProperty(key, computedStyle_fixed[key], 'important')
);

其他注意事项

不建议创建像computedStyle_fixed这样的隐式全局变量,声明它们或将它们设置为 object 属性。

使用JSON.stringify创建 object 的浅表副本也不是一个好主意,使用Object.assign会更好:

let computedStyle_fixed = Object.assign({}, computedStyle);

这也会创建一个普通的 object,而不是CSSStyleDeclaration object。

据我了解,您需要元素的所有 css 属性并存储在 object 中。

您可以使用扩展运算符来执行此操作。

const computedStyle = {...window.getComputedStyle(input_element)};

您现在可以像使用普通 object 一样使用它。

例如: console.log(computedStyle.backgroundColor);

我已经解决了,我只是稍微改变了retrieve_color() function。 但我认为它将输入边框的样式设置为与最初一样。 如果您查看 jsfiddle 的代码并单击 change_color 然后单击retrieve_color,您会看到输入看起来不像原来的样子(边框不同)。 你知道我怎样才能把它恢复原样吗?

// the code    
https://jsfiddle.net/gfxjn4se/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM