如何动态更改样式表中CSS属性的值?

时间:2012-01-10 01:32:17

标签: javascript css class

如果我有css:

.myclass
{
background: #FF00FF;
}

和html:

<div class="myclass">etc.</div>
<div class="myotherclass">etc.</div>
<div class="myclass">etc.</div>

如何将myclass的背景变量更改为其他颜色,以便该类的所有div都会更改其背景?

请不要jquery,谢谢

2 个答案:

答案 0 :(得分:5)

你走了:

[].every.call( document.styleSheets, function ( sheet ) {
    return [].every.call( sheet.cssRules, function ( rule ) {
        if ( rule.selectorText === '.myclass' ) {
            rule.style.backgroundColor = 'green';
            return false;
        }
        return true;
    });
});

现场演示: http://jsfiddle.net/gHXbq/

ES5-shim for IE8

答案 1 :(得分:0)

希望我接近你所期待的,当我说你可以尝试这样的事情: -

&#13;
&#13;
$(document).ready(function(){
    $("button").click(function(){
        $("div").toggleClass("myclass");
    });
});
&#13;
.myclass
    {
       background: #FF00FF;
    }
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>
<body>

<button>Set the color property of all p elements</button>

<div class="myclass">etc.</div>
<div class="myotherclass">etc.</div>
<div class="myclass">etc.</div>



</body>
</html>
&#13;
&#13;
&#13;