正确处理cssRules与JavaScript

时间:2014-03-03 06:57:10

标签: javascript css dom

我正在使用Javascript处理CSS规则,在每个resize事件中,我创建了一个可能已经在CSS或之前的Javascript resize事件中定义的类,这导致在一些resize事件之后有太多的CSS规则。如何更改我的代码,以便删除预先存在的CSS规则或修改它们。

这是我在StackOverflow上找到的代码。

var setStyleRule = function(selector, rule) {
    var stylesheet = document.styleSheets[(document.styleSheets.length - 1)];
    if(stylesheet.addRule) {
        stylesheet.addRule(selector, rule)
    } else if(stylesheet.insertRule) {
        stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
    }
};

1 个答案:

答案 0 :(得分:1)

在页面中添加一个空样式标记,其中包含一些ID,如

<style id="customstyles"  type="text/css"></style>

然后在resize事件处理程序 -

var sheets = document.styleSheets;
for (var i = 0; i < sheets.length; i++) {
    var sheet = sheets[i];
    if (sheet.ownerNode.id == "customstyles") {
        var rules = sheet.cssRules;
        if (rules.length > 0) {
            // instead of addRule, modify the existing rule with following code-
            var style = "css attribute on which you are applying new value";
            var stylevalue = "the value to be applied";
            for (var j = 0; j < rules.length; j++) {
                var rule = rules[j];
                if (rule.selectorText == selector) {
                    rule.style.setProperty(style, stylevalue);
                    break;
                }
            }
        }
        else {
            // call you code to insert new cssRule
            stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
        }
        break;
    }
}

希望有所帮助