开发者

Why does jQuery.cssRule plugin have to add rules to all style-sheets?

I tried to use $.cssRule() plugi开发者_StackOverflow社区n and found that it makes it inconvenient to debug those rules in FireBug because each rule appears to be attached to every css file loaded on my page and consequently defined many times.

Source code shows that it does that on purpose inside that for loop: for(var i = 0; i < document.styleSheets.length; i++) ... insertRule ...

Why can't it add new own style-sheet and then add rules to it ?

If it's necessary for rules prioritization then why not shuffle style sheets ?

I noticed the same issue here so unless those 2 places come from same source which had a bug, I wonder why it is necessary to do it that way.


I think I remember why I did like this in the answer you have linked to. I'm not just adding a new rule, I'm adding a new rule to an existing declaration. So I had to look up every stylesheet in order to find that declaration. Now, the best optimization that I can come up with right now, is to read the styleSheets in reverse order, and break the loop after the first encounter of that selectorText. This way, you modify just one stylesheet, the one with the highest precedence.

var ss = document.styleSheets;

for (var i=ss.length-1; i>=0; i--) {
    var rules = ss[i].cssRules || ss[i].rules;

    for (var j=0; j<rules.length; j++) {
        if (rules[j].selectorText === ".classname") {
            rules[j].style.color = "green";
            break;
        }
    }
}

Anyway, this assumes that the order of the stylesheet objects in the collection is the inverse of the order of precedence, which I believe it is.


Here is another way to add rules or styles and avoid multiple instances to be inserted.

var newRule = 
    'body {' +
        'background: rgb(231, 225, 218);' +
        'padding:3px !important;' +
    '}';

$('<style id="tamper"></style>').appendTo('head');
$('style#tamper').append(newRule);

You create a style with an id, then you append your rules or styles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜