0

我需要遍历一个网格,并将更改应用于每一行的子级。例如,如果我有一个 3 行的网格,我怎样才能使它每行的孩子可以是不同的颜色?这是一些用于创建网格的基本 HTML + CSS 的 JSFiddle。我想做这样每一行都是不同的颜色。

http://jsfiddle.net/onestepcreative/24Ljw/6/

想法?提前致谢!

4

3 回答 3

3

这是一个带有简单 javascript 的版本。您也可以使用 nth-child 选择器仅使用 CSS 执行此操作

http://jsfiddle.net/24Ljw/8/

于 2012-07-07T01:13:42.207 回答
0

你听说过 createTreeWalker 吗?https://developer.mozilla.org/en/DOM/document.createTreeWalker

此方法允许您迭代 DOM 中的节点而无需递归。

不过,您正在寻找的可能是一个循环。这里是原生 js。

//Get the elements
var grids = document.querySelectorAll(".grid_row > div"); 

// Make up the colors
var colors = [
    "#fff", "#000", "#666", "#555", 
    "#f4f4f4", "#111", "#222", "#333", 
    "#f0f0f0", "#f2f2f2", "#f8f8f8", "#010101"
];

// Turn it into an array and not a nodeList
grids = Array.prototype.slice.apply(grids);

// Loop over the array
grids.forEach(function(grid, i) {
    grid.style.backgroundColor = colors[i];                
});

​</p>

于 2012-07-07T01:33:10.207 回答
0

这是一个将类“灰色”附加到奇数行的小提琴

http://jsfiddle.net/24Ljw/9/

于 2012-07-07T01:17:50.957 回答