我如何使用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