2012-10-30 48 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