简体   繁体   English

是否有任何JavaScript库可解析jQuery中使用的CSS规则?

[英]Is there any JavaScript library for parsing css rules for use in jQuery?

The goal is to pollyfill css3 nth-child pseudo-class with jQuery. 目标是使用jQuery来填充css3第n个子伪类。 So I need to parse css rules and reapply them with jQuery for older browsers that do not support nth-child directly from css. 因此,我需要解析css规则并使用jQuery重新应用它们,以用于不直接从css直接支持nth-child的旧版浏览器。 So I wrote some code, but I am pretty sure that something similar should be already present for example at github. 所以我写了一些代码,但是我很确定应该有类似的东西出现在github上。 May be someone already encountered such a problem? 可能有人已经遇到过这样的问题? Here is my code: 这是我的代码:

        // if ie7 or ie8
        if (!$.support.leadingWhitespace) {         

            var aStyleSheetList = document.styleSheets,
                aRules = [],
                current = '',
                aSelectors = [];

            for (var i = 0; i < aStyleSheetList.length; i++) {
                aRules = aStyleSheetList[i].cssRules || aStyleSheetList[i].rules;
                for (var j = 0; j < aRules.length; j++) {
                    current = aRules[j];
                    if (current.selectorText && current.selectorText.indexOf('nth-child') !== -1) {
                        aSelectors.push([current.selectorText, current.cssText.substring(current.cssText.indexOf('{') + 1, current.cssText.indexOf('}'))]);
                    }
                }
            }

            var jqCssObject = {},
                declarations = [],
                keyValuePair = [];

            for (var k = 0; k < aSelectors.length; k++) {
                declarations = aSelectors[k][1].split(';');
                for (var m = 0; m < declarations.length; m++) {
                    keyValuePair = declarations[m].split(':');
                    jqCssObject[keyValuePair[0]] = keyValuePair[1];
                }
                $(aSelectors[k][0]).css(jqCssObject);                   
            }

        }

If you want to use pseudo-selectors such as nth-child in older browsers, one option is to use Selectivizr : 如果要在较旧的浏览器中使用伪选择器(例如nth-child ,则一种选择是使用Selectivizr

"Selectivizr is a JavaScript utility that emulates CSS3 pseudo-classes and attribute selectors in Internet Explorer 6-8." “ Selectivizr是一个JavaScript实用程序,它可以在Internet Explorer 6-8中模拟CSS3伪类和属性选择器。”

As you're already using jQuery, all you have to do is include the Selectivizr <script> in your page and you will have compatibility for various pseudo/attribute selectors in older browsers. 由于您已经在使用jQuery,因此您所要做的就是在页面中包含Selectivizr <script> ,并且您将与旧版浏览器中的各种伪/属性选择器兼容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM