使用循环获取每个子元素的样式属性

Get style property of each children using loop

本文关键字:元素 样式 属性 循环 获取      更新时间:2023-09-26

我正在尝试获取每个子元素的背景色。

var arr = [];
for(var c = 0; c < 5; c++){
    var temp = div.children[c].style.backgroundColor;
    arr[c] = temp;
}

我似乎不明白为什么它不工作,因为当我使用下面的代码时,它工作了

div.children[c].style.backgroundColor = "#eee";

Window.getComputedStyle() 方法在应用活动样式表并解析这些值可能包含的任何基本计算后,给出元素的所有 CSS 属性的值。

HTMLElement.style 属性返回一个CSSStyleDeclaration对象,该对象只表示 element's inline style attribute ,忽略任何应用的样式规则。


HTMLElement.style只适用于inline-css,使用 getComputedStyle(Element) 获取与Element相关的所有style对象。

注意:我将使用Array#push而不是在指定的index赋值。

var arr = [];
for (var c = 0; c < 5; c++) {
  var temp = getComputedStyle(div.children[c]).backgroundColor;
  arr.push(temp);
}

避免自定义创建数组的替代方法。

Array.map.call

var div = document.getElementById("text");
var arr = Array.prototype.map.call(div.children, function(el) {
  return window.getComputedStyle(el).backgroundColor;
})
console.log(arr)
<div ID="text">
  <span style="background-color:rgb(200,20,20)">1</span>
  <span style="background-color:rgb(250,150,150)">2</span>
  <span style="background-color:rgb(150,100,0)">2</span>
</div>