2013-03-12 93 views
0

我拉着我的头发,试图解决一个简单的问题。我知道这里有一些数学步骤,我错过了,我觉得我正处在解决方案的边缘,但我无法到达那里。收缩盒子

我想要做的是写一个算法来填充正方形的元素,一旦元素被填充,调整正方形的大小,创建一个新的行并继续填充。一旦两个新行都被填充,追加另一行。基本上是一个换行型算法?

所以我到目前为止工作的第一行,但之后失败,因为它不断调整不必要的。

$(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

后在问题本身的一些代码,请。 – Blazemonger 2013-03-12 16:07:49

+0

@Blazemonger有警告(主要是关于分号),但没有错误。 – Barmar 2013-03-12 16:16:20

回答

2

这里的问题:

//will go over columns? 
if (index >= columns) { 

这是计数错误时,有超过一排。试试这个:

//will go over columns? 
if (index >= Math.floor(columns)*rows) { 

http://jsfiddle.net/mblase75/zXeHG/

+1

Bah,Blazemonger打败了我。我建议的一个建议是在评估列下降时执行Math.floor。你永远不希望它是非整数。 – 2013-03-12 16:23:25

+0

我知道我错过了简单的事情。谢谢! – thebringking 2013-03-12 16:23:33