我正在拔头发,试图解决一个简单的问题。我知道这里有一些数学步骤,我缺少了,我觉得我在解决方案的边缘是正确的,但我无法到达那里。
我要做的是编写一个算法来填充带有正方形的元素,一旦元素被填充,调整正方形的大小,创建一个新行并继续填充。填充两个新行后,添加另一行。基本上是换行类型算法?
所以我到目前为止在第一行上工作,但在那之后失败,因为它不断地调整大小。
$(function(){ //DOM Ready
//get columns of even squares
var columns = parseInt($(".grid").width()/$(".grid").height());
var rows = 1;
function checkSize(ico,index){
var grid,gridWidth,gridHeight
var icon,iconWidth,iconHeight
//get our grid info
grid = $(".grid");
gridWidth = grid.width();
gridHeight= grid.height();
//get our icon info
icon = $(ico);
iconWidth = icon.outerWidth();
iconHeight = icon.outerHeight();
//will go over columns?
if(index >= columns){
//do we need another row?
if(Math.floor(gridHeight/iconHeight) === rows){
//add row
rows++;
//reset columns
columns = gridWidth / Math.floor(gridHeight / rows);
//resize boxes
size();
};
}
};
function size(){
var grid,icon,newHeight;
grid = $(".grid");
newHeight = (grid.height()/rows)
$.each(grid.children(".icon"),function(index,value){
icon = $(value);
icon.css("height",newHeight+'px');
icon.css("width",newHeight+'px');
});
}
//fill
var counter = 0;
function fillGrid(){
var icon,grid,r,g,b,a
icon = $('<div class="icon"></div>');
//random color
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
a = 1;
icon.css('background-color','rgba('+r+','+g+','+b+','+a+')')
grid = $(".grid");
grid.append(icon);
size(icon);
checkSize(icon,counter);
counter++;
};
var timeoutID;
function start(){
if(timeoutID){
clearInterval(timeoutID);
timeoutID = undefined;
}else{
timeoutID = window.setInterval(fillGrid, 1000);
}
};
//START THE TIMER
$('#start').on('click',start);
});
请参阅此处的工作示例 -
http://jsbin.com/ovewib/7/edit
非常感谢任何帮助!
答案 0 :(得分:2)
问题在于:
//will go over columns?
if (index >= columns) {
当有多行时,这是错误的。试试这个:
//will go over columns?
if (index >= Math.floor(columns)*rows) {