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

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

2016-04-19 12:44 591 查看
来源: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方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: