用javascript動態向頁面添加CSS樣式
<div id="test">測試用JS向頁面添加樣式</div>
<script type="text/javascript">
var f=function(){
var styleElems=document.getElementsByTagName("style");
if(styleElems.length==0){
var tempStyle=document.createElement("style");
tempStyle.setAttribute("type","text/css");
document.getElementsByTagName("head")[0].appendChild(tempStyle);
}
//如果頁面中沒有STYLE標簽,則在HEAD中插入STYLE標簽
var styleElem=styleElems[0];
//這里直接用數組的第一個元素
if(styleElem.styleSheet){//IE
styleElem.styleSheet.cssText+="#test{width:200px; height:50px; background:#0f0;}";
//alert("ie");
}else {
styleElem.appendChild(document.createTextNode("#test{width:200px; height:50px; background:#0f0;}"));
//alert("webkit");
}
}
setTimeout(f,3000);
</script>
注意:
在IE中向CSS樣式中添加用 styleElem.styleSheet.cssText="";
在其他瀏覽器中用styleElem.appendChild(document.createTextNode(""));
為什么需要這么麻煩的向STYLE中添加樣式呢 ?為什么不直接用doc.style.color="red";這樣的形式呢,主要原因是直接加在元素STYLE中的樣式優先級要比樣式表的優先級高,這樣在改變CSS的時候可能會出錯。
附:
1. 判斷瀏覽器是不是IE if(!+"\v1") 為true則是IE
2.setAttribute(name,value) 和 getAttribute(value)
var input=document.createElement("input");
input.setAttribute("type","text");//設置屬性
input.setAttribute("value","123");
var value=input.getAttribute("value"); //獲取屬性
可以使用setAttribute()設置屬性,getAttribute()獲取屬性,但是不能用setAttribute()設置元素的類名
input.setAttribute("class","w960");瀏覽器不兼容,可以使用 input.className="w960";代替