Entire (completely) overwrite CSS styles

后端 未结 3 864
忘掉有多难
忘掉有多难 2021-01-06 08:06

How can I overwrite an entire CSS style for a class, id or other CSS selector?

For example:

If in styles1.css I have:

/* also, t         


        
3条回答
  •  半阙折子戏
    2021-01-06 08:47

    Tested to work with IE9, Chrome and Opera. I had a problem with this when I wrote it, so decided that rather than changing existing rules, that I'd just append a new rule after the existing ones. From memory, the problem was with the default browser found in Android 2.3

    Altering an existing rule seemed to be a better(cleaner) solution, though appending new rules ultimately proved to be chosen path. (I was changing background images by creating images with a canvas and then setting the background-image property. The images could be quite large, hence the preference for update)

    Function

    function replaceRuleAttrib(ruleSelector, attribText, newValue)
    {
        var nSheets, nRules, sheetNum, curSheet, curStyle, curAttrib;
        var nSheets = document.styleSheets.length;
    
        if (nSheets == 0)
            document.head.appendChild(document.createElement('style'));
        else
        for (sheetNum = 0; sheetNum

    Sample CSS (before)

    
    

    Usage:

    function onHeadingClick()
    {
        replaceRuleAttrib('h1', 'color', 'green');
    }
    

    Sample CSS (after)

    
    

提交回复
热议问题