我创建了一个jQuery函数,用于检索网页中使用的颜色:
$('*').each(function(i, el){
var $element = $(el),
color = $element.css('background-color');
if(!~$.inArray(color, colors))
colors.push(color);
});它对我来说工作得很好。现在我需要把这段代码转换成纯javascript,我写了这个:
var elements = Array.prototype.slice.call(document.getElementsByTagName('*')),
len = elements.length,
i, node, color;
for (i = 0; i < len; i++) {
node = elements[i];
color = node.style.backgroundColor;
if (color && !~colors.indexOf(color)) {
colors.push(color);
}
}但是,对于每个元素,元素node.style.backgroundColor都是空的,就像下面的屏幕截图所示

为什么在jquery中一切都完成了,而使用javascript转换脚本却不能很好地工作?
发布于 2014-11-26 19:17:14
您应该对css样式使用getComputedStyle方法,因为node.style.backgroundColor仅适用于内联样式(如此问题Javascript - getting the background color of the hovered element中所建议的)。
//try this
getComputedStyle(target).backgroundColorhttps://stackoverflow.com/questions/27147654
复制相似问题