说明我们先来看看出了什么问题。
<!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 - 用于操作单个元素的样式(e09f610c1071f06618b1a5247b8a280b);
(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'],这样就不受“-”的影响了,所以也能获取到属性值。
以上就是background-color 与 backgroundcolor的有什么区别的详细内容。