如何在行内样式中找到共同点
how to find common in inline styles?
我有一个顺序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/
相关文章:
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 将样式表插入iframe
- 跟踪在页面加载时应用内联样式的JavaScript
- 如果文本字段为空,则使用JavaScript应用CSS样式
- 定义完全独立的样式信息
- W3C循环样式的JavaScript
- jQuery/JavaScript在线公文包表单-打印样式表
- 使用递归、Ramda.js和无点样式重构字符串的getPermutations()
- FF和Chromium中CSS样式按钮的外观差异
- 如何首先设置样式<td>表中包含在窗体中的元素
- javascript问题正文样式
- 使用具有内联样式的tidy-html5
- DataTables-创建自定义分页样式(加载更多样式)
- 具有所有样式的文本正在复制到可编辑文本区域
- 如何提供在javascript中编写对对象的重复访问以设置元素样式的简写
- 绑定Range输入以修改样式
- 一个正则表达式,用于从JS中的HTML标记中删除id、样式和类属性
- 不同页面背景的body标记上的角度ng样式
- 列表样式在IE中未设置为none,但在IE中适用
- 如何在行内样式中找到共同点