如何检测覆盖的css属性?

bur*_*mre 3 javascript css firebug stylesheet google-chrome-devtools

我可以使用document.stylesheets获取元素的所有css属性,但其中一些不活动,因为这些属性被覆盖.在firebug中(chrome开发者工具也有这个功能),如果有一个覆盖的css属性,你会看到类似的东西: 在此输入图像描述

我能想到的唯一方法是比较元素(在jQuery中$(element).css(property))和定义的css属性的活动css属性,document.stylesheets但它不是一种可靠的方法.有什么建议吗?

Bea*_*rtz 5

在webkit中,您可以使用getMatchedCSSRules来实现您想要的.它按照浏览器应用的继承顺序返回CSS规则集,它是webkit检查器不久前使用的.对于像Firefox这样的基于Gecko的浏览器,虽然我没有对它进行过测试,但似乎可以在这里使用polyfill .

一个基本的工作解决方案

以下代码也可作为小提琴使用

因为getMatchedCSSRules 只能使用内联样式表,所以首先必须内联链接的样式表:

function inlineStyles() {
    var stylesheets = document.getElementsByTagName('link'),
        head = document.getElementsByTagName('head')[0];

    for (var i = 0; i < stylesheets.length; i++) {
        if (stylesheets[i].getAttribute('rel') == 'stylesheet') {
            (function (stylesheet) {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", stylesheet.getAttribute('href'), true);
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        var inlineStyle = document.createElement('style');
                        inlineStyle.setAttribute('type', 'text/css');
                        inlineStyle.innerText = xmlhttp.responseText;
                        head.replaceChild(inlineStyle, stylesheet);
                    }
                };
                xmlhttp.send();
            })(stylesheets[i]);
        } else {
            continue;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

然后,大块:这是第一枪,随意改进.它可以处理inherit规则和最多一个!important定义,但就是这样.对于非常复杂的设置,这将不得不改进:

function getStyle(s, id) {
    var element = typeof id === 'string' ? document.getElementById(id) : id,
        css = window.getMatchedCSSRules(element),
        style = window.getComputedStyle(element),
        value = style[s],
        styles = [],
        rules = [],
        inherited, currentRule;

    // if there's a computed style, start calculation
    if (value) {

        // add matched rules if there are any
        if (css) {
            for (var i = 0; i < css.length; i++) {
                styles.push(css[i]);
            }
        }

        // add the element style attribute as a matched rule
        styles.push({
            style: element.style,
            cssText: 'element.style {' + element.getAttribute('style') + ' }'
        });

        for (var i = styles.length - 1; i >= 0; i--) {
            var def = styles[i],
                rule = {
                    index: rules.length,
                    style: s,
                    value: styles[i].style[s],
                    cssText: def.cssText
                };

            if (rule.value == 'inherit' && !currentRule) {
                if (inherited = getInherited(element, s, value)) {
                    rule.inheritedFrom = inherited;
                    currentRule = rule;
                    inherited = undefined;
                } else {
                    rules.push(rule);
                }
            } else if (rule.value == 'inherit' && currentRule && isImportant(s, value, def.cssText)) {
                if (inherited = getInherited(element, s, def)) {
                    rule.inheritedFrom = inherited;
                    rules.splice(currentRule.index, 0, currentRule);
                    currentRule = rule;
                    inherited = undefined;
                } else {
                    rules.push(rule);
                }
            } else if (rule.value == value && !currentRule) {
                currentRule = rule;
            } else if (rule.value == value && currentRule && isImportant(s, value, def.cssText)) {
                rules.splice(currentRule.index, 0, currentRule);
                currentRule = rule;
            } else if (rule.value.length) {
                rules.push(rule)
            }
        }

        return {
            current: currentRule,
            overwritten: rules
        };

    } else {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果正在进行继承,我们走向DOM节点以找到使用此帮助函数定义CSS规则的元素并获取其样式:

function getInherited(element, s, value) {
    while (element.parentNode && window.getComputedStyle(element.parentNode)[s] == value) {
        element = element.parentNode;
    }

    if (element) {
        return getStyle(s, element).current;
    } else {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

我们确定是否使用此辅助函数将CSS规则标记为重要:

function isImportant(s, style, text) {
    return new RegExp(s.replace(/([A-Z])/g, '-$1').toLowerCase() + ':\\s+' + style + '\\s+!important').test(text)
}
Run Code Online (Sandbox Code Playgroud)

看看小提琴看它是否正常工作