How to dynamically change the value of a CSS property inside a stylesheet?

前端 未结 2 729
走了就别回头了
走了就别回头了 2021-01-06 17:57

If I have css:

.myclass
{
background: #FF00FF;
}

And html:

etc.
相关标签:
2条回答
  • 2021-01-06 18:16

    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

    0 讨论(0)
  • 2021-01-06 18:20

    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>

    0 讨论(0)
提交回复
热议问题