How to dynamically change the value of a CSS prope

2019-02-15 03:00发布

If I have css:

.myclass
{
background: #FF00FF;
}

And html:

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

How can I change the background variable of myclass to another color, so that all div's of that class get their background changed?

no jquery please, thanks

2条回答
疯言疯语
2楼-- · 2019-02-15 03:11

Here you go:

[].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;
    });
});

Live demo: http://jsfiddle.net/gHXbq/

ES5-shim for IE8

查看更多
太酷不给撩
3楼-- · 2019-02-15 03:17

Hope I am close to what you are expecting when I say You may please try something like this:-

$(document).ready(function(){
    $("button").click(function(){
        $("div").toggleClass("myclass");
    });
});
.myclass
    {
       background: #FF00FF;
    }
<!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>

查看更多
登录 后发表回答