您的位置:首页 > Web前端 > JavaScript

利用原生JavaScript获取样式的方式小结

2014-10-06 00:14 471 查看
来源:http://www.ido321.com/930.html

ps:是获取样式,不是设置样式。若没有给元素设置样式值,则返回浏览器给予的默认值。(论坛整理)

1、element.style:只能获取写在元素标签中的style属性里的样式值,无法获取到定义在<style></style>和通过<link href=”css.css”>加载进来的样式属性

[code] var ele = document.getElementById('ele');

ele.style.color;    //获取颜色

[/code]

2、window.getComputedStyle():可以获取当前元素所有最终使用的CSS属性值。

[code] window.getComputedStyle("元素", "伪类");

[/code]

这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“:before”) 。如果不需要伪元素信息,第二个参数可以是null。也可以通过document.defaultView.getComputedStyle(“元素”, “伪类”);来使用

[code] var ele = document.getElementById('ele');

var styles = window.getComputedStyle(ele,null);

styles.color;  //获取颜色

[/code]

可以通过style.length来查看浏览器默认样式的个数。IE6-8不支持该方法,需要使用后面的方法。对于Firefox和Safari,会把颜色转换成rgb格式。

3、element.currentStyle:IE 专用,返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的<style>属性等)。

[code] var ele = document.getElementById('ele');

var styles = ele.currentStyle;

styles.color;

[/code]

注意:对于综合属性border等,ie返回undefined,其他浏览器有的返回值,有的不返回,但是borderLeftWidth这样的属性是返回值的

4、getPropertyValue():获取CSS样式的直接属性名称

[code] var ele = document.getElementById('ele');

window.getComputedStyle(ele,null).getPropertyValue('color');

[/code]

注意:属性名不支持驼峰格式,IE6-8不支持该方法,需要使用下面的方法

5、getAttribute():与getPropertyValue类似,有一点的差异是属性名驼峰格式

[code] var test = document.getElementById('test');

window.getComputedStyle(test, null).getPropertyValue("backgroundColor");

[/code]

注意:该方法只支持IE6-8。

下面的获取样式方法兼容IE、chrome、FireFox等

[code] function getStyle(ele) {

var style = null;


if(window.getComputedStyle) {

style = window.getComputedStyle(ele, null);

}else{

style = ele.currentStyle;

}


return style;

}

[/code]

在JQuery中,常用css()获取样式属性,其底层运作就应用了getComputedStyle以及getPropertyValue方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: