javascipt修改css级联样式表类和伪类样式

  javascript修改级联样式表文件或者内嵌级联样式表中定义的类样式属性。需要注意的是级联样式中的伪类直接替换属性值无效,需要新增样式进行覆盖,替换值不起作用

<!doctype html>
<title>javascipt修改css级联样式表类和伪类样式</title>
<style>
.exampleA{color:Blue}
.exampleA:before {content:"-";color:red;font-size:20px;font-weight:bold}
</style><!--IE条件注释,判断是否IE8浏览器-->
<!--[if IE 8]><script>var IE8=true</script><![endif]-->
<script>
    function changecss(theClass, element, value) {
        var sl = document.styleSheets.length;
        if (sl == 0) return;
        var isPseudo = theClass.indexOf(':') != -1;//css伪类
        //非IE8-,js获取到伪类名称包含二个冒号
        if (window.IE8) theClass = theClass.replace(/:+/g, ':');
        else theClass = theClass.replace(/:+/g, '::');
        var cssRules = document.styleSheets[0].rules ? 'rules' : 'cssRules';
        for (var i = 0; i < sl; i++) {
            for (var j = 0, rl = document.styleSheets[i][cssRules].length; j < rl; j++) {
                if (document.styleSheets[i][cssRules][j].selectorText == theClass) {
                    if (isPseudo) //css伪类需要覆盖,替换值没用
                        document.styleSheets[i].addRule ?
                            document.styleSheets[i].addRule(theClass, element + ':' + value) ://IE8+,chrome
                            document.styleSheets[i].insertRule(theClass + '{' + element + ':' + value + '}', rl);//firefox
                    else document.styleSheets[i][cssRules][j].style[element] = value;
                    break;
                }
            }
        }
    }
 </script>
 
<span class="exampleA">Example A</span><br />
<span class="exampleB">Example B</span><br />
<span class="exampleA">Example A</span><br />
<input type="button" value="修改exampleA为红色" onclick="changecss('.exampleA','color','red')"/>
<input type="button" value="修改exampleA为黑色" onclick="changecss('.exampleA','color','black')" />
<input type="button" value="修改exampleA:before伪类color为blue" onclick="changecss('.exampleA::before','color','blue')" />
<input type="button" value="修改exampleA:before伪类color为red" onclick="changecss('.exampleA::before','color','red')" />

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:javascipt修改css级联样式表类和伪类样式

评论(0)Web开发网
阅读(618)喜欢(0)JavaScript/Ajax开发技巧