如何在行内样式中找到共同点

how to find common in inline styles?

本文关键字:共同点 样式      更新时间:2023-09-26

我有一个顺序dom元素节点数组,它可能有也可能没有内联样式。我需要最终得到一个对象或数组,其中只有所有节点共有的键和值。需要在IE8+, chrome和FF中工作。

我甚至不能得到一个节点样式到一个数组没有一堆其他的东西被包括在内。

我已经尝试使用节点[x]。样式,但它似乎返回了许多无关的东西和其他问题。

//g is node array
s=[];
for(k in g)
  {
  if(g.hasOwnProperty(k) && g[k]) s[k]=g[k];
  }
console.log(s);

给了我["font-weight", cssText: "font-weight: bold;", fontWeight: "bold"],这是接近的,但我只想要fontWeight:"粗体"在数组中。在任何情况下,这只适用于chrome。

我目前唯一的想法是使用cssText和分号分裂和分号分裂,但这似乎是一个丑陋和缓慢的方式来做到这一点,特别是因为我需要比较一堆节点,并做同样的样式。

所以,我希望有人能想出一个简单优雅的解决方案来解决第一段提出的问题。

如果你真的只想要在对象的HTML中内联指定的样式,那么你将不得不处理style属性的文本。

.style属性将显示比对象本身指定的样式更多的样式(显示一些样式的默认值),所以你不能使用它。

下面是一个函数,它接受一个DOM节点的集合,并返回一个通用样式的映射(样式是内联指定的,并且在每个对象上具有相同的属性和值):

function getCommonStyles(elems) {
    var styles, styleItem, styleCollection = {}, commonStyles = {}, prop, val;
    for (var i = 0; i < elems.length; i++) {
        var styleText = elems[i].getAttribute("style");
        if (styleText) {
            // split into an array of individual style strings
            styles = styleText.split(/'s*;'s*/);
            for (var j = 0; j < styles.length; j++) {
                // split into the two pieces of a style
                styleItem = styles[j].split(/'s*:'s*/);
                // only if we found exactly two pieces should we count this one
                if (styleItem.length === 2) {
                    prop = styleItem[0];
                    val = styleItem[1];
                    // if we already have this style property in our collection
                    if (styleCollection[prop]) {
                        // if same value, then increment the cntr
                        if (styleCollection[prop].value === val) {
                            ++styleCollection[prop].cntr;
                        }
                    } else {
                        // style tag didn't exist so add it
                        var newTag = {};
                        newTag.value = val;
                        newTag.cntr = 1;
                        styleCollection[prop] = newTag;
                    }
                }
            }
        }
    }
    // now go through the styleCollection and put the ones in the common styles
    // that were present for every element
    for (var prop in styleCollection) {
        if (styleCollection[prop].cntr === elems.length) {
            commonStyles[prop] = styleCollection[prop].value;
        }
    }
    return(commonStyles);
}

工作演示:http://jsfiddle.net/jfriend00/JW7CZ/