JS 插入CSS样式的方法

来源:互联网 发布:自我测评软件 编辑:程序博客网 时间:2024/06/05 07:59

JS 插入CSS样式的方法

方法一:存在style标签,获取此style标签,然后通过innerHTML内容插入css样式:

<style id="mystyle">    </style>    <script type="text/javascript">        var sty=document.getElementById("mystyle");        sty.innerHTML+="div{width:200px;height:200px;background:red;border:solid 2px red}";    </script>    <div>This is a div</div>

结果:这里写图片描述

注意:style标签得在script代码前,不然会引起错误Uncaught TypeError: Cannot read property ‘innerHTML’ of null,或者使用window.onload,那就可以随便放style与script的位置也可以。

相关代码:

<script type="text/javascript">        window.onload=function(){            var sty=document.getElementById("mystyle");        sty.innerHTML+="div{width:200px;height:200px;background:red;border:solid 2px red}";        }    </script>    <style id="mystyle"></style>

方法二:不要求页面中已经存在style标签,动态创建新的style标签。

<div id="div1">div1</div><div id="div2">div2</div>

JS代码:

window.onload=function(){            //方法一:        var sty=document.getElementById("mystyle");        sty.innerHTML+="#div1{width:200px;height:200px;background:red;border:solid 2px black}";        //方法二:        var insertCSS=function(cssStyle){            var style=document.createElement("style");            var theHead=document.head||document.getElementsByTagName('head')[0];            style.type="text/css";//IE需要设置            if(style.styleSheet){  //IE                var ieInsertCSS=function(){                    try{                    style.styleSheet.cssText=cssStyle;                    }catch(e){                    }                };            //若当前styleSheet不能使用,则放到异步中                if(style.styleSheet.disable){                    setTimeout(ieInsertCSS,10);                } else{                    ieInsertCSS();                }             } else{ //W3c浏览器                style.appendChild(document.createTextNode(cssStyle));                theHead.appendChild(style);            }        }        insertCSS("#div2{width:200px;height:200px;background:yellow;border:solid 2px black}")    }

方法二结果:
这里写图片描述

对IE来说style和script节点是特殊的节点,不允许访问其子节点,因此,IE会在添加子节点的时候报错。
style.appendChild(document.createTextNode(cssStyle));
解决IE的这个问题就是访问元素的styleSheet属性,该属性又有cssText属性,可用于接收CSS代码。在赋值CSS代码之前,IE还需要将style节点的type属性设置为“text/css”
html元素:

0 0
原创粉丝点击