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

JavaScript中如何用原生的js获取style样式

2017-08-17 15:37 435 查看
1. Element.style——只能获取内联样式

该方法只能获取到内联样式,而无法获取到<style></style>和<link href="">中的样式

例如:

<h1 onclick="getStyle(this)" style="color: red
a5a7
">测试</h1>
function getStyle(obj){
var color=obj.style.color;
alert(color)
}
但是当没有内联样式时,则无法获取到默认样式,
function getStyle(obj){
var backgroundColor=obj.style.backgroundColor;
alert(backgroudColor);//空白
obj.style.backgroundC='blue';
alert(backgroundColor);//空白
}

2. getComputedStyle()——获取最终样式,包括内联样式,不支持IE6-8

语法:window.getComputedStyle("元素", "伪类");

当不需要伪类是,第二个参数可以设置为null

function getStyle(obj){
var color=window.getComputedStyle(obj,null).backgroundColor
alert(color);//rbga(0,0,0,0)
}

也可以使用document.defaultView.getComputedStyle("元素", "伪类");

3. Element.currentStyle——适用于IE,可获取内联样式,返回最终样式

function getStyle(obj){
var backgroundColor=obj.currentStyle.backgroundColor
alert(backgroundColor);//rbg(0,0,0)
}

4. getPropertyValue()——不支持驼峰格式,不支持IE6-8
function getStyle(obj){
var backgroundColor=window.getComputedStyle(obj,null).getPropertyValue('background-color')
alert(backgroundColor);//rbga(0,0,0,0)
}

5. getAttribute——支持驼峰样式,与getPropertyValue()类似

为了兼容IE6-8,可以使用下面的方式获取样式

function getStyle(obj){
if(window.currentStyle){
style=window.currentStyle(obj,null);
}else{
style=window.getComputedStyle(obj,null)
}
return style;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: