我如何使用jQuery实现这个网格并使用.css()方法添加该背景?jQuery数学和拆分只返回请求的元素
我试过使用eq()
或index()
或filtering()
但我不能只返回我需要的网格元素。
我需要只返回角元素和中间我需要返回每个元素分开处理。
我如何使用jQuery实现这个网格并使用.css()方法添加该背景?jQuery数学和拆分只返回请求的元素
我试过使用eq()
或index()
或filtering()
但我不能只返回我需要的网格元素。
我需要只返回角元素和中间我需要返回每个元素分开处理。
您必须迭代所有单元格并使用if
语句来检查应该将附加到该单元格的背景。请参阅JSFiddle。
/*
Here are some global variables
c - Array of rows in the table
x - Temporary x-coordinate used in loop (left is 0, right is c.length - 1)
y - Temporary y-coordinate used in loop (top is 0, bottom is c.length - 1)
c1 - Distance from x-axis translated to center of the table
c2 - Distance from y-axis translated to center of the table
cols - An array of RGB colors
*/
var c = $('.row'), x, y, c1, c2,
cols = [
135, 203, 205,
235, 164, 158,
197, 191, 88,
214, 117, 165
];
// Iterate over all cells
for(y = 0; y < c.length; y++) for(x = 0; x < c.length; x++){
// Calculate x-distance and y-distance from the center
c1 = Math.abs(x - 2.5);
c2 = Math.abs(y - 2.5);
// If we are in the corner, color it in one way
if(c1 > 1 && c2 > 1) x < 3 ? setBg(x, y, 166, 233, 197) : setBg(x, y, 168, 156, 197);
// Otherwise use `cols` variable
else if(c1 < 1 && c2 < 1) setBg(x, y, cols.shift(), cols.shift(), cols.shift());
}
// This function set background to cell at (x, y) from RGB value
function setBg(x, y, r, g, b){
c[y].children[x].style.background = 'rgb(' + r + ',' + g + ',' + b + ')';
}
你已经拥有的第一个角是如何着色的例子。通过更改循环的索引,您可以为其他角落着色。
for (var i = 0; i < c.length - 4; i++) {
for (var j = 0; j < c.length - 4; j++) {
...
}
}
试着想一下如何访问4个中间单元格并给它们各自的颜色。
你可以看看这里有四个色角的jsfiddle:https://jsfiddle.net/wzztoch8/。
我会亲自创建一个函数来帮助这里 - > 例如。
function fill(x1,y1,x2,y2,color) {
$('.row:nth-child(n+'+y1+'):nth-child(-n+'+y2+
') span:nth-child(n+'+x1+
'):nth-child(-n+'+x2+')')
.css({"background-color":color})
}
fill(0,0,2,2,'#00ffcc');
fill(0,5,2,6,'yellow');
您需要迭代单元格并检查循环索引是否等于特定单元格的索引,添加您的css。 – Mohammad