js操作css样式

在介绍js操作css样式之前,我先给大家介绍一下css样式在网页html中是如何加载的,在html页面中加载css样式可以分为三种表现形式,分别为:内嵌样式(Inline Style)、内部样式(Internal Style Sheet)、外联样式(External Style Sheet)。

内嵌样式即为在DOM元素中直接添加style属性来改表元素效果,如:<div style="color:#f00">内嵌样式</div>。它只能改变该元素样式。

内部样式即在页面中添加css样式,如:在页面中添加<style type="css/text">div{color:#f00}</style>。它可以改变整个页面元素效果。

外联样式即加载外部css样式文件,它有两种方式加载外部样式,一种是:<link rel="stylesheet" type="text/css" href="test.css" /> ,另一种是:<style type="css/text">@import test.css</style>。

最后我们来说说js如何操作css样式的。 

1、js操作内嵌样式。

<script type="text/javascript">

document.getElementById('test').style.color = '#000';

</script>

2、js操作内部样式。

<script type="text/javascript">

方法一: 

 

function getStyle(selector, attr) {
for(i = 0, len = document.styleSheets.length; i < len; i++) {
var rules;
if(document.styleSheets[i].rules) {
/*for ie*/ 
rules = document.styleSheets[i].rules;
} else {
/*for 非ie*/
rules = document.styleSheets[i].cssRules;
}
for(j = 0, rlen = rules.length; j < rlen; j++) {
if(rules[j].selectorText == selector) {
alert(rules[j].style[attr]);
}
}
}
}

 

</script>

方法二:

<script type="text/javascript">

IE:elementObj.currentStyle

w3c标准:window.getComputedStyle(elementObj, null)  或 document.defaultView.getComputedStyle(elementObj, null )

document.defaultView.getComputedStyle?document.defaultView.getComputedStyle(id,null).getPropertyValue("background-color"):id.currentStyle["backgroundColor"]; 

</scirpt> 
 

3、js操作外联样式。

posted @ 2011-11-16 11:05  吊儿郎当  阅读(8673)  评论(0编辑  收藏  举报