我创建了一个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转换脚本不能正常工作?
答案 0 :(得分:0)
您应该对{c}样式使用getComputedStyle
方法,因为node.style.backgroundColor
仅适用于内联样式(如此问题Javascript - getting the background color of the hovered element中所述)
//try this
getComputedStyle(target).backgroundColor