简体   繁体   English

JavaScript计算固定div中矩形的高度和宽度

[英]JavaScript calculate height & width of rectangles in fixed div

I have a problem which may be more algebra than code, but here goes. 我有一个问题,可能是代数而不是代码,但是这里有。

I need to calculate the best fit for x columns and y rows in a div of fixed proportions (say 300px x 300px). 我需要以固定比例的div(比如300px x 300px)计算x列和y行的最佳拟合。 In other words, I have a div of 300px x 300px, which is the parent container of n child divs, which can be x columns by y rows. 换句话说,我有一个300px x 300px的div,它是n个子div的父容器,可以是y列的x列。

Based on user interaction, the number of columns and the number of rows can change. 根据用户交互,列数和行数可以更改。 Upon each interaction I need to recalculate the dimensions of the inner panels so as the ratio (1.69) remains constant and the panels make most efficient use of the available space (parent div). 在每次交互时,我需要重新计算内部面板的尺寸,以便比率(1.69)保持不变,并且面板最有效地利用可用空间(父div)。

I can always get the number of columns and the number of rows and can adjust the panel height and width css accordingly. 我总是可以获得列数和行数,并可以相应地调整面板高度和宽度css。

I know there is a simple algebraic calculation for this but it escapes me, and I'm no JavaScript expert. 我知道有一个简单的代数计算,但它逃脱了我,我不是JavaScript专家。 I have tried various implementations using jQuery, but I keep getting lost. 我已经尝试过使用jQuery的各种实现,但我一直迷路。 I'm not asking for the exact answer - any pointers would be helpful. 我不是要求确切的答案 - 任何指针都会有所帮助。

This must be your answer: 这一定是你的答案:

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

You may check it here: http://jsfiddle.net/3fxDL/ 你可以在这里查看: http//jsfiddle.net/3fxDL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM