我正在寻找一种从网站获取所有CSS颜色的方法。到目前为止,可以使用document.styleSheets处理内部样式表和外部样式表。问题在于,通过css样式属性直接分配给标签的样式将不在此列表中。
是否有比遍历DOM的所有元素并解析每个标签的style属性更好的方法?你还有其他建议吗?
此函数将返回通过内联样式或CSS类声明的rgb / rgba颜色数组
function getAllColors() {
// regex via http://stackoverflow.com/a/7543829/149636
var rgbRegex = /^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/;
var allColors = [];
var elems = document.getElementsByTagName('*');
var total = elems.length;
var x,y,elemStyles,styleName,styleValue,rgbVal;
for(x = 0; x < total; x++) {
elemStyles = window.getComputedStyle(elems[x]);
for(y = 0; y < elemStyles.length; y++) {
styleName = elemStyles[y];
styleValue = elemStyles[styleName];
if(!styleValue) {
continue;
}
// convert to string to avoid match exceptions
styleValue += "";
rgbVal = styleValue.match(rgbRegex);
if(!rgbVal) { // property does not contain a color
continue;
}
if(allColors.indexOf(rgbVal.input) == -1) { // avoid duplicate entries
allColors.push(rgbVal.input);
}
}
}
return allColors;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句