![](/img/trans.png)
[英]Calculate height of div with absolute child divs that have no height set
[英]Have child divs fill parent div with set proportions
我想用jQuery / javascript創建一個函數,該函數將用隨機大小的子div填充父div,這些子div相加父的大小。
例如,10個子div用於填充比例為1200px x 600px的容器div
<div class="container">
<!-- 10 child divs with random height and width. -->
</div>
您可以使用將矩形分割為兩個子矩形,然后遞歸地將其分割的函數。
function fillWithChilds(el, N) { function rand(n) { /* weight=100 means no random weight=0 means totally random */ var weight = 50; return Math.floor(weight*n/2+n*(100-weight)*Math.random())/100; } function main(N, x, y, hei, wid) { if(N < 1) return; if(N === 1) { var child = document.createElement('div'); child.className = 'child'; child.style.left = x + 'px'; child.style.top = y + 'px'; child.style.width = wid + 'px'; child.style.height = hei + 'px'; el.appendChild(child); return; } var halfN = Math.floor(N/2); if(wid > hei) { var newWid = rand(wid); if(2*newWid > wid) halfN = N-halfN; main(halfN, x, y, hei, newWid); main(N-halfN, x+newWid, y, hei, wid-newWid); } else { var newHei = rand(hei); if(2*newHei > hei) halfN = N-halfN; main(halfN, x, y, newHei, wid); main(N-halfN, x, y+newHei, hei-newHei, wid); } } main(N, 0, 0, el.clientHeight, el.clientWidth); } fillWithChilds(document.getElementById('wrapper'), 11);
#wrapper { background: #ccf; position: relative; height: 300px; width: 400px } .child { background: #cfc; outline: 2px solid red; position: absolute; }
<div id="wrapper"></div>
分發會很痛苦。 我認為那里有一個處理其中某些問題的jQuery庫...我會四處看看。 不過,這是一個非常有趣的問題。
這就是我到目前為止所做的事情。 這有點稀疏。
試圖確定應該構建更多組件的部分是粗糙的部分。 我試圖盡量減少循環:
var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;
// width
while (elementWidth < containerSize.x)
{
var size = generateElement();
elementWidth += size.x;
elementHeight += size.y;
}
// height, if not already full
while (elementHeight < containerSize.y)
{
var size = generateElement();
elementWidth += size.x;
elementHeight += size.y;
}
清理了一下。 再次檢查小提琴: http : //jsfiddle.net/twPQ7/2/
// determine the size of the container
var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;
// iteratively generate elements until we've hit the width of the container
while (elementWidth < containerSize.x)
{
var size = generateElement();
elementWidth += size.x;
// keep track of the tallest element.
if (size.y > elementHeight) elementHeight = size.y;
}
// iteratively generate elements until we've hit the height of the container
while (elementHeight < containerSize.y)
{
var size = generateElement();
elementHeight += size.y;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.