大家都知道,用document.getElementById(‘element’).style.xxx可以获取元素的样式信息,可是它获取的只是DOM元素style属性里的样式规则,对于通过class属性引用的外部样式表,就拿不到我们要的信息了。
DOM标准里有个全局方法getComputedStyle,可以获取到当前对象样式规则信息,如:window.getComputedStyle(obj,null).paddingLeft,(obj代表获取的节点名,第二个参数代表获取伪元素信息,如‘:after’,不需要就null)就能获取到对象的左内边距。
但是事情还没完,万恶的IE不支持此方法,它有自己的一个实现方式,那就是currentStyle,不同于全局方法getComputedStyle,它是作为DOM元素属性存在的,如:obj.currentStyle.paddingLeft,在IE中就获取到对象的左内边距了。具体的兼容性写法就留给你们自己研究了。
而控制的方法就是统一的,如:obj.style.width='200px';
需要注意的就是CSS中用横线连接的属性如:line-height:10px;在js中就要写成obj.style.lineHeight='10px';
下面就是具体的CSS和JS对照的属性的写法。
而对于CSS3新添加的属性需要写浏览器前缀。
如-webkit-transform:rotate(20deg); js对应的写法为obj.style.webkitTransform='rotate(20deg)';
但是我发现最新的火狐浏览器不识别obj.style.mozTransform='rotate(20deg)';
而识别obj.style.MozTransform='rotate(20deg)';
所以我建议写前缀还是第一个字母大写,如Ms、Moz、Webkit,至少这三大浏览器都识别这种写法,其它的我没测试过。
CSS语法 (不区分大小写) JavaScript语法 (区分大小写)
border border
border-bottom borderBottom
border-bottom-color borderBottomColor
border-bottom-style borderBottomStyle
border-bottom-width borderBottomWidth
border-color borderColor
border-left borderLeft
border-left-color borderLeftColor
border-left-style borderLeftStyle
border-left-width borderLeftWidth
border-right borderRight
border-right-color borderRightColor
border-right-style borderRightStyle
border-right-width borderRightWidth
border-style borderStyle
border-top borderTop
border-top-color borderTopColor
border-top-style borderTopStyle
border-top-width borderTopWidth
border-width borderWidth
clear clear
float floatStyle
margin margin
margin-bottom marginBottom
margin-left marginLeft
margin-right marginRight
margin-top marginTop
padding padding
padding-bottom paddingBottom
padding-left paddingLeft
padding-right paddingRight
padding-top paddingTop
颜色和背景标签和属性对照
CSS语法 (不区分大小写) JavaScript语法 (区分大小写)
background background
background-attachment backgroundAttachment
background-color backgroundColor
background-image backgroundImage
background-position backgroundPosition
background-repeat backgroundRepeat
color color
样式标签和属性对照
CSS语法 (不区分大小写) JavaScript语法 (区分大小写)
display display
list-style-type listStyleType
list-style-image listStyleImage
list-style-position listStylePosition
list-style listStyle
white-space whiteSpace
文字样式标签和属性对照
CSS语法 (不区分大小写) JavaScript语法 (区分大小写)
font font
font-family fontFamily
font-size fontSize
font-style fontStyle
font-variant fontVariant
font-weight fontWeight
文本标签和属性对照
CSS语法 (不区分大小写) JavaScript语法 (区分大小写)
letter-spacing letterSpacing
line-break lineBreak
line-height lineHeight
text-align textAlign
text-decoration textDecoration
text-indent textIndent
text-justify textJustify
text-transform textTransform
vertical-align verticalAlign
其中有什么错误的地方还望大家指出。
本文介绍了如何使用JavaScript操作CSS样式,包括通过document.getElementById及getComputedStyle方法获取样式信息,以及如何处理不同浏览器间的兼容性问题。

409

被折叠的 条评论
为什么被折叠?



