JavaScript中如何用原生的js获取style样式
2017-08-17 15:37
435 查看
1. Element.style——只能获取内联样式
该方法只能获取到内联样式,而无法获取到<style></style>和<link href="">中的样式
例如:
2. getComputedStyle()——获取最终样式,包括内联样式,不支持IE6-8
语法:window.getComputedStyle("元素", "伪类");
当不需要伪类是,第二个参数可以设置为null
也可以使用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;
}
该方法只能获取到内联样式,而无法获取到<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;
}
相关文章推荐
- 如何用js获取元素样式(get.ComputedStyle()和currentStyle方法)
- 原生js如何实现柱状图以及原生js柱状图结合ajax循环动态数据_JavaScript_柱状图(原生JavaScript做的柱状图)(03)_ajax获取数据
- 获取css样式表内样式的js函数currentStyle(IE),defaultView(FF)
- 原生javascript设置获取行间样式及非行间样式的写法
- 由于 box.style.left只能获取行内样式的值,不能获取到css中JS中样式left等值;用JS获取外部CSS样式--currentStyle和getComputedStyle的兼容写法
- Javascript如何用一个优雅的姿势通过getStyle函数来获取元素的样式
- JS如何客服克服兼容性获取非行间样式
- 利用原生JavaScript获取样式的方式小结
- 如何获取与修改元素样式(写在style文件)
- JavaScript通过style只能获取内联 状态的样式
- 原生JS如何更准确的获取CSS样式
- 获取css样式表内样式的js函数currentStyle(IE),defaultView(FF)
- 原生JS中如何获取CSS属性中的值
- iOS 基于JavaScriptCore 不等webView加载完毕就交互,网页获取原生内容。 webView的高级用法之JS交互,js与oc的相互调用
- [JavaScript] 用js如何获取当前url地址中的域名
- JS 获取style 里面的样式
- 总结获取原生JS(javascript)的父节点、子节点、兄弟节点
- JavaScript如何做表格即时编辑,原生js的表格即时编辑怎么做
- 原生javascript获取元素样式
- 原生js获取元素样式