![](/img/trans.png)
[英]how to calculate the height of a div with some text inside and a fixed width
[英]JavaScript calculate height & width of rectangles in fixed div
我有一個問題,可能是代數而不是代碼,但是這里有。
我需要以固定比例的div(比如300px x 300px)計算x列和y行的最佳擬合。 換句話說,我有一個300px x 300px的div,它是n個子div的父容器,可以是y列的x列。
根據用戶交互,列數和行數可以更改。 在每次交互時,我需要重新計算內部面板的尺寸,以便比率(1.69)保持不變,並且面板最有效地利用可用空間(父div)。
我總是可以獲得列數和行數,並可以相應地調整面板高度和寬度css。
我知道有一個簡單的代數計算,但它逃脫了我,我不是JavaScript專家。 我已經嘗試過使用jQuery的各種實現,但我一直迷路。 我不是要求確切的答案 - 任何指針都會有所幫助。
這一定是你的答案:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(
function ()
{
$("#go_btn").click(
function ()
{
var height = Math.round(300 / $("#h").val())-2;
var width = Math.round(300 / $("#w").val())-2;
//-2 is because of allocating space for borders.
var div = $("<div></div>");
$("#container").html('');
for (i = 0; i < $("#h").val(); i++)
{
for (j = 0; j < $("#w").val(); j++)
{
$("#container").append('<div style="border:1px dotted green;text-align:center;vertical-align:center;float:left;width:' + width + 'px;height:' + height + 'px;">' + i + ' x ' + j + '</div>');
}
}
});
});
</script>
<style>
#container {
width: 300px;
height:300px;
border: 1px solid grey;
}
</style>
<p>Width:
<input type="text" id="w" class="inp" />
</p>
<p>Height:
<input type="text" id="h" class="inp" />
</p>
<p>
<input type="button" value="Go" id="go_btn" />
</p>
<div id="container"></div>
你可以在這里查看: http : //jsfiddle.net/3fxDL/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.