用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";代替