簡體   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