標籤:ref 屬性 asc pre win style font load alert
樣式表有三種:
內嵌樣式:<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來擷取,當然也可以擷取內嵌樣式。
擷取css樣式,style、getComputedStyle及currentStyle的區別