我正在寻找一种从网站获取所有 css 颜色的方法。到目前为止,可以使用 document.styleSheets 处理内部和外部样式表。问题是通过 css 样式属性直接分配给标签的样式不会在此列表中。
有没有比遍历 DOM 的所有元素并解析每个标签的样式属性更好的方法?您还有其他想法吗?
最佳答案
此函数将返回通过内联样式或 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;
}
关于javascript - 获取所有样式属性颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23842320/