簡體   English   中英

Javascript Element.style CSSStyleDeclaration 對象的屬性看起來很奇怪?

[英]Javascript Element.style CSSStyleDeclaration object's properties look wierd?

假設我在 HTML 文件中有一個按鈕,

<button id="btn">Click Me</button>

使用 JavaScript 將該按鈕的顏色更改為紅色。

const btn = document.querySelector('#btn');
btn.style['background-color'] = 'red';

然后我檢查btn.style['background-color'] 它顯示red

btn.addEventListener('click', () => {
    console.log(`This button is in ${btn.style['background-color']}`)
});

所以我想我的btn.style object 應該是這樣的,

{
...
"background-color": "red",
...
}

但是當我在控制台中打印它們時,為什么鍵值對是0: "background-color" ,而值red又在哪里?

btn.addEventListener('click', () => console.dir(btn.style));

在此處輸入圖像描述

CSSStyleDeclaration object 有點異國情調。 如果您直接查看btn.style["background-color"]btn.style.backgroundColor ,您會看到red (或紅色的某種表示形式,因瀏覽器而異)。

 const btn = document.querySelector('#btn'); btn.style['background-color'] = 'red'; btn.addEventListener('click', () => { console.log(btn.style["background-color"]); console.log(btn.style.backgroundColor); });
 <button id="btn">Click Me</button>

在您顯示的控制台 output 中,您會在backgroundColor下找到它:

控制台輸出顯示 backgroundColor: red 周圍有一個圓圈

如果您查看 CSSStyleDeclaration 的規范,您會在 JavaScript 中了解更多處理 CSS 的內部工作原理。

這些是 JS 為保存您的 CSS styles 而采取的步驟:

  1. 如果您提供屬性名稱的駝峰式版本,則CSS 屬性到 IDL 屬性算法會將字符串轉換為破折號,以便以后使用

  2. 調用setProperty(property, value, priority)方法,property 是屬性名稱的破折號版本(例如background-color ),而 value 是屬性應該設置為不帶!important標志的值(例如"red" )

  3. 屬性被推送到內部 NodeList 結構CSSDeclaration中,其中包含屬性名稱、值、重要標志和區分大小寫的標志

  4. 現在,樣式被計算出來了,這主要取決於瀏覽器的實現,對屬性順序和映射邏輯(這里)有一定的限制,當然還有其他關於元素應該如何表現的規范

現在,為了訪問這些屬性,在內部,有一個包含所有計算屬性的數組以及前面提到的 NodeList 來通過它們的屬性名稱獲取值。 訪問這些的方法是item(index)

這就是為什么,當您在控制台上查看 CSSStyleDeclaration 時,頂部有一個0: "background-color" ,它是元素的 NodeList 中的第一個(計算的)屬性,所以e.style.item(0)將返回"background-color"

如果現在要獲取屬性的值,可以使用getPropertyValue(property) ,它遍歷 NodeList 並找到具有相應屬性名稱的項目並返回它的值。

JavaScript has short-hands for these function, through the Object index ( here ), so e.style[property] runs the getPropertyValue() for that property name, and through an Array index for the item(index) method, so e.style[index]運行item()方法。

 const btn = document.querySelector('#btn'); btn.style['background-color'] = 'red'; btn.addEventListener('click', () => { console.log(btn.style[0], btn.style.item(0)); console.log(btn.style[btn.style[0]], btn.style.getPropertyValue(btn.style.item(0))); });
 <button id="btn">Click Me</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM