我拉着我的頭髮,試圖解決一個簡單的問題。我知道這裏有一些數學步驟,我錯過了,我覺得我正處在解決方案的邊緣,但我無法到達那裏。收縮盒子
我想要做的是寫一個算法來填充正方形的元素,一旦元素被填充,調整正方形的大小,創建一個新的行並繼續填充。一旦兩個新行都被填充,追加另一行。基本上是一個換行型算法?
所以我到目前爲止工作的第一行,但之後失敗,因爲它不斷調整不必要的。
$(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
任何幫助將不勝感激!
後在問題本身的一些代碼,請。 – Blazemonger 2013-03-12 16:07:49
@Blazemonger有警告(主要是關於分號),但沒有錯誤。 – Barmar 2013-03-12 16:16:20