样式表有三种:
内嵌样式:<div id="box" style="color:red">box</div>,style写在html中的为内嵌样式;
内联样式:
<style>
#box{
font-size: 25px;
background-color: #ccc;
}
</style>
在html页中直接写入<style></style>的为内联样式;
外部样式:<link rel="stylesheet" href="css/style.css" />这种为外部样式。
现在来测试一个小例子:
<style>
#box{
font-size: 25px;
background-color: #ccc;
}
</style>
<div id="box" style="color:red">box</div>
js代码:
window.onload=function(){
var box=document.getElementById('box');
alert(box.style.color); //弹出red element.style[attr]对内嵌样式有效
alert(box.style.fontSize); //弹出空 从这里可以看出element.style[attr]只对内联样式无效
alert(isStyle(box,'color')); //使用isStyle方法,弹出rgb(255,0,0)
alert(isStyle(box,'fontSize')); //使用isStyle方法,弹出25px
}
/*通过元素节点和属性获取属性值*/
function isStyle(ele,attr){
if(window.getComputedStyle!='undefined'){ //兼容firefox
return window.getComputedStyle(ele,null)[attr];
}else if(ele.currentStyle!='undefined'){ //兼容IE
return ele.currentStyle[attr];
}
}
要想获取内部样式以及外部样式需要通过getComputedStyle和currentStyle来获取,当然也可以获取内嵌样式。