2012-10-30 45 views
2

我正在尝试使水平并排的DIVs成为块状&垂直&我设法做到了这一点,而div的高度相同。但是当一个div有更大的高度和宽度时,它会变成另一个div,而这些div应该在&之下。这是问题的一个样本(http://givemeaudience.com/test.html)&下面是我的代码:使用javascript或jQuery的固体阻挡DIV使用javascript或jQuery

<!doctype html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Test</title> 
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> 
<style> 
    body{margin:0px;padding:0px;font-family:Verdana, Geneva, sans-serif;font-size:12px;} 
    #container{position:relative;} 
    #container .box{width:143px;height:143px;background:#eee;padding:5px;position:absolute;} 
    #container .s21{width:303px;} 
    #container .s32{width:463px;height:303px;background:#F60;} 
</style> 
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> 

<script type="text/javascript"> 
    function relocate(){ 
     var browserWidth = $(window).width(); 
     var defaultWidth = 160; 
     var yPos = 7; 
     var xPos = 7; 
     $('.box').each(function(i, obj) { 
      elementWidth = $(this).width(); 

      if(xPos + elementWidth > browserWidth){ 
       yPos = yPos + 160; 
       xPos = 7; 
      } 
      $(this).css('top',yPos+'px'); 
      $(this).css('left',xPos+'px'); 

      xPos = xPos + 17 + $(this).width(); 
     }); 
    } 

    $(document).ready(function(){ 
     relocate(); 
     $(window).resize(function() { 
      relocate(); 
     }); 
    }); 
</script> 

</head> 

<body> 

<div id="container"> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box s32" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 
<div class="box" id=""> 
    Test 
</div> 

</div> 

</body> 
</html> 

在此先感谢。

+0

你能给出一个更好的解释(也许有图片)你想要发生什么吗?我不遵循你的解释。此外,演示超链接不适合我。 – nnnnnn

+3

也许你正在寻找:http://masonry.desandro.com/。 – pimvdb

+0

这正是我正在寻找的。非常感谢pimvdb –

回答

0

如果你想在#container中压缩你的.box文件,更好的解决方案 - 将它们显示为“inline-block”,并按照你的需要(向左或向右)浮动。但是你应该知道,之前的块顺序应该是专门的。 这里简单的CSS框对齐:

#container { 
    white-space: nowrap; 
} 
.box { 
    white-space: auto;   
    display: inline-block; 
    vertical-align: top; 
    float:left; 
} 

http://jsfiddle.net/iegik/DBkXU/

无论如何,如果你想立即重新排序,箱子大小通常应该为 - 预定义的宽度和高度(例如,XS,S,M, L,XL,XXL - 尺寸)。然后将它们放在矩阵中:

[ 2x1, 0, 1x2, 1x3 ], 
[ 1x1, 1x2, 0, 0 ], 
[ 1x1, 0, 1x1, 0 ] 
+0

blocks_in_row = row_width/block_width; – iegik