JavaScript获取当前应用于元素的样式列表 [英] JavaScript get list of styles currently applied to an element

查看:105
本文介绍了JavaScript获取当前应用于元素的样式列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了很多方法来将样式应用于元素,但结果空白.

I've tried many things to get the styles applied to an element but have come up blank.

除非您可以解决垃圾退货问题,否则请不要将 getComputedStyle 视为解决方案.

Please do not cite getComputedStyle as being a solution unless you can solve the junk returns issue.

主要问题是 window.getComputedStyle(document.querySelector('ANY ELEMENT')).fill 将返回"rgb(0,0,0)" ,几乎在任何情况下都不是正确的样式,并且没有明显的方法来区分是否实际应用了该样式.

The primary problem is that window.getComputedStyle(document.querySelector('ANY ELEMENT')).fill will return "rgb(0, 0, 0)", which is not the correct style in almost any instances, and has no apparent way to destinguish if its actually being applied or not.

以上示例不是唯一的问题案例; getComputedStyle 返回的大量规则都是错误的,如果应用这些规则,将会大大改变页面的外观.

The above example is not the only problem case; there are tons of rules returned by getComputedStyle which are wrong and will drastically change the look of the page if they are applied.

不能进行静态解析,因为在某些情况下.css文件位于另一台没有跨域标头的服务器上;这也隐藏了通常在 document.styleSheets 中找到的样式.

Static parsing is not an option as there are cases where the .css files are on another server with no cross-origin headers; which also hides styles usually found in document.styleSheets.

有什么方法可以获取已应用样式的列表吗?

Is there any way to get a list of the applied styles and nothing else?

根据要求,以下代码将演示该问题(在Chrome上):

var all = document.getElementsByTagName('*');
for(var i in all)
    if (all[i].style) all[i].style.cssText = window.getComputedStyle(all[i]).cssText;

我的答案包含适用于所有浏览器的代码.我保留上面的内容以保留评论主题.

My answer has code which works on all browsers. I keep above to preserve comment thread.

推荐答案

部分答案(已更新):

可以通过调用我的函数 getRenderedStyles 来仅获取活动样式:

getRenderedStyles 现在绕过活动的样式表以获得更准确的输出.

getRenderedStyles now bypasses active stylesheets for more accurate output.

function getRenderedStyles(element) {
    var tmpele, tmpstyle, elestyle, varstyle, elecolor, eletag;
    var styles   = {};
    var defstyle = {};
    elestyle   = window.getComputedStyle(element);
    elecolor   = elestyle.color; 
    eletag     = element.tagName;
    var frag = document.createDocumentFragment();
    frag.appendChild(document.documentElement);
    tmpele   = document.appendChild(document.createElement(eletag));
    tmpstyle = window.getComputedStyle(tmpele);
    styles['color']     = elecolor===tmpstyle.color?undefined:elecolor;
    tmpele.style.color  = elecolor; // workaround for color propagation on other styles 
    for (var i in tmpstyle)
        defstyle[i] = tmpstyle[i];
    tmpele.remove();
    document.appendChild(frag);
    varstyle = element.style;
    for (var i in varstyle) {
        if ((((typeof varstyle[i])==="string"))&&(i!=="cssText")) {
            if ((defstyle[i]!==elestyle[i]))
                styles[i] = elestyle[i];
        }
    }
    return styles;
}

由于在某些情况下浏览器似乎仍然返回无效的样式,因此很遗憾.通常会移动元素的位置.

Sadly there's a caviat as the browser still seemingly returns invalid styles in some cases. Often shifting the locations of elements.

要验证这一点,您可以运行以下代码,考虑到父/子继承,以尝试将当前样式正确地应用于页面:

To verify this you may run the following code, which takes into account parent/child inheritance, in an attempt to properly apply the current styles to the page:

function DOMDepth(element) {
    var cur  = element;
    var deep = 0;
    while(cur.parentNode)
        deep++, cur = cur.parentNode;
    return deep;
}

function getElementsByDepth() {
    var all = document.getElementsByTagName('*');
    var depth_map = {};
    var deepest   = 0;
    for(var i in all) {
        var depth = DOMDepth(all[i]);
        deepest   = depth>deepest?depth:deepest;
        depth_map[depth] = depth_map[depth] || [];
        depth_map[depth].push(all[i]);
    }
    depth_map['deepest'] = deepest;
    return depth_map;
}

function inlineComputedStyles() {
    var depth_map = getElementsByDepth();
    for (var i = depth_map.deepest; i>0; i--) {
        var elements = depth_map[i];
        for (var j in elements) {
            var styles = getRenderedStyles(elements[j]);
            for (var k in styles) {
                elements[j].style[k] = styles[k];
            }
        }
    }
}

我已经测试了前面的内容,并且可以确认它没有遇到问题中代码片段的颜色问题.令人遗憾的是,我不确定为什么某些要素仍会转移或是否有解决方法.

I have tested the preceeding and can confirm it does not suffer the color problems of the snippet in the question. Sadly I am uncertain as to why some elements still shift or if there's a way to fix it.

特别感谢Kit Fung指出继承问题.

Special thanks to Kit Fung for pointing out the inheritance problem.

这篇关于JavaScript获取当前应用于元素的样式列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆