background-color 與 backgroundColor的有什麼區別

來源:互聯網
上載者:User


說明

我們先來看看出了什麼問題。

<!doctype html><html lang="zh"> <head>     <meta charset="utf-8"> </head> <body style="background-color:red;"> </body> <script>    var a = document.querySelector('body');    var CamelCase = a.style.backgroundColor;    console.log('駝峰命名結果:'+CamelCase);    var CSSProperty = a.style['background-color'];    console.log('CSS文法結果:'+CSSProperty); </script></html>

結果圖:

可能你還沒覺得那裡奇怪,我們再來看看 a.style 是什麼,

上面的是一部分,沒有全部截出來,因為實在太長了,主要是想說,在a.style 這個對象中並沒有看見 background-color 這樣的屬性呀! 為什麼 a.style['background-color'] 居然也能擷取到值,這是很奇怪的事。

解釋

經過各種查資料,終於算是明白了,這主要是因為 CSSStyleDeclaration 做了 介面擴充,讓 IDL屬性 能夠擷取和設定 瀏覽器支援的 CSS屬性。

CSSStyleDeclaration

CSSStyleDeclaration 表示一個CSS屬性索引值對的集合。它被用於一些API中:

  • HTMLElement.style - 用於操作單個元素的樣式(<elem style="...">);

  • (TODO: reword) 作為 declaration block 的介面,當規則為CSSStyleRule 時,由stylesheet中的 style 屬性返回 。

  • CSSStyleDeclaration也是由window.getComputedStyle()返回的唯讀介面。

IDL

介面描述語言(Interface description language,縮寫IDL),是CORBA規範的一部分,是跨平台開發的基礎。
IDL是用來描述軟體組件介面的一種電腦語言。IDL通過一種中立的方式來描述介面,使得在不同平台上啟動並執行對象和用不同語言編寫的程式可以相互連信交流;比如,一個組件用C++寫成,另一個組件用Java寫成。

在 CSSOM 中這樣寫到

For example
if the user agent supports the -webkit-transform
property, there would be a webkitTransform IDL attribute. There would
also be a WebkitTransform IDL attribute because of the rules for
camel-cased attributes.

例如
如果使用者代理程式支援-webkit-transform 屬性,因為駝峰命名的規則 會有webkitTransform IDL屬性。也會有一個WebkitTransform IDL屬性

說到這裡大家應該明白點了。
我們最開始 a.style,a的style屬性的值是一個對象。
這個對象所包含的屬性與CSS規則一一對應,但是名字需要用駝峰命名的方式進行改變,比如background-color寫成backgroundColor。改寫的規則是將橫杠從CSS屬性名稱中去除,然後將橫杠後的第一個字母大寫。如果CSS屬性名稱是JavaScript保留字,則規則名之前需要加上字串css,比如float寫成cssFloat,而改寫後的 backgroundColor 就是 IDL屬性。

注意: “-” 在JS 中 是 減法的意思,變數名中是不能用“-”的

總結

說了這麼多概念,我們簡單理解就是, 像backgroundColor 與 background-color 這樣的屬性,他們的屬性值是一樣的,改變兩個中任何一個屬性的值,另一個屬性的值也會隨之改變,但是JS中變數不能用“-”,所以可以通過每個CSS屬性 對應的 IDL屬性,來擷取和設定 CSS屬性,所以JS 有background-color 這樣的屬性,只是不能這樣顯示出來,但是我們最開始的寫成 a.style['background-color'],這樣就不受“-”的影響了,所以也能擷取到屬性值。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.