Как динамически добавлять div внутри div, пока ширина и высота родительского div не будут заполнены / заполнены - PullRequest
0 голосов
/ 29 апреля 2018

Фон: Я делаю веб-страницу, где пользователь будет вводить плитку Ширина и высота и Ширина и высота этажа. Этаж Ширина и высота используется для расчета площади этажа. Вход плитки в дюймах, а вход в полу в футах.

Техническая информация: Я установил 1 фут, равный 60 пикселям, и 1 дюйм, равный 5 пикселям для расчетов.

Где я сейчас? Прямо сейчас я застрял в рисовании всех плиток (дочерние элементы) в области (родительские элементы) . Сейчас я использую простой цикл for для создания плиток (div's) .

Пока что вывод выглядит примерно так ...

enter image description here

Что я хочу? Что ж, я пытаюсь сделать так, чтобы, когда пользователь нажимает кнопку «Рассчитать», он / она видит дизайн пола. Позже я буду раскрашивать и добавлять шаблоны.

Вывод должен быть таким: (извините, если границы не совпадают, это было сделано с помощью Windows Paint) :

enter image description here

Код:

        $(document).ready(function () {
            $("#btnCalculate").click(function (e) { 
                e.preventDefault();

                $("#area").empty();

                const foot = 60, inch = 5;

                let tileW = parseFloat($("#tileWidth").val());
                let tileH = parseFloat($("#tileHeight").val());

                let areaW = parseFloat($("#areaWidth").val());
                let areaH = parseFloat($("#areaHeight").val());
                
                $("#area").css("height", (foot * areaH));
                $("#area").css("width", (foot * areaW));


                for (let r = 0; r<10  ; r++) {
                    // const element = array[r];
                    $("#area").append("<div id='tile_"+r+"' style='width:"+((inch * tileW))+"px; height:"+((inch * tileH))+"px;' class='border_color'> </div>");
                    
                }
            });
        });
#area {
            border: 1px solid black;
            height: 25px;
            width: 25px;
        }
        .border_color{
            /* border: 1px solid black; */
            outline: 1px solid; /* use instead of border */
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Tile Width (inches): </p><input type="numbers" id ="tileWidth" placeholder="Tile Width" value="6">
    <p>Tile Height (inches): </p><input type="numbers" id ="tileHeight" placeholder="Tile Height" value="4">
    <br>
    <p>Area Width (foot): </p><input type="numbers" id ="areaWidth" placeholder="Area Width" value="11.5">
    <p>Area Height (foot): </p><input type="numbers" id ="areaHeight" placeholder="Area Height" value="6.5">
    <button id="btnCalculate" >Calculate</button>
        
    

    <div id="area">

    </div>

Внешняя ссылка скрипта: https://jsfiddle.net/22gLkguL/

Я пытался заархивировать все это, но не смог ..! Кто-нибудь, пожалуйста, помогите мне ИЛИ направьте меня на правильный путь ...?

Ответы [ 2 ]

0 голосов
/ 29 апреля 2018

Используйте display: flex и flex-wrap: wrap

#area {
  border: 1px solid black;
  height: 25px;
  width: 25px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

и вычислите число div с, которые каждая сторона (ширина или высота) может быть заполнена максимально.

$(document).ready(function() {
  $("#btnCalculate").click(function(e) {
    e.preventDefault();

    $("#area").empty();

    const foot = 60,
      inch = 5;

    let tileW = parseFloat($("#tileWidth").val());
    let tileH = parseFloat($("#tileHeight").val());

    let areaW = parseFloat($("#areaWidth").val());
    let areaH = parseFloat($("#areaHeight").val());
    
    var areaHeight = (foot * areaH)
    var areaWidth = (foot * areaW)
    var divHeight = (inch * tileH)
    var divWidth = (inch * tileW)
    
    $("#area").css("height", areaHeight);
    $("#area").css("width", areaWidth);

    var nums = Math.floor(areaWidth/divWidth) * Math.floor(areaHeight/divHeight)

    for (let r = 0; r < nums; r++) {
      var $div = $('<div>', {
        id: 'tile_' + r,
        class: 'border_color',
        height: divHeight,
        width: divWidth,
      })
      $("#area").append($div);

    }
  });
});
#area {
  border: 1px solid black;
  height: 25px;
  width: 25px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.border_color {
  outline: 1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Tile Width (inches): </p><input type="numbers" id="tileWidth" placeholder="Tile Width" value="6">
<p>Tile Height (inches): </p><input type="numbers" id="tileHeight" placeholder="Tile Height" value="4">
<br>
<p>Area Width (foot): </p><input type="numbers" id="areaWidth" placeholder="Area Width" value="11.5">
<p>Area Height (foot): </p><input type="numbers" id="areaHeight" placeholder="Area Height" value="6.5">
<button id="btnCalculate">Calculate</button>



<div id="area">

</div>
0 голосов
/ 29 апреля 2018

используйте display: flex; flex-wrap: wrap для элемента площади.

и рассчитать количество плиток как ---

(areaWidthInPixels / tileWidthinPixels) * (AreaHeightInPixels / tileHeightinPixels)

        $(document).ready(function () {
            $("#btnCalculate").click(function (e) { 
                e.preventDefault();

                $("#area").empty();

                const foot = 60, inch = 5;

                let tileW = parseFloat($("#tileWidth").val());
                let tileH = parseFloat($("#tileHeight").val());

                let areaW = parseFloat($("#areaWidth").val());
                let areaH = parseFloat($("#areaHeight").val());
                
                $("#area").css("height", (foot * areaH));
                $("#area").css("width", (foot * areaW));
                
                let noOfTiles = Math.floor( ((foot * areaW)/(inch * tileW)) )* Math.floor( ((foot * areaH)/(inch * tileH)) );
								
                alert("noOf TIles :: " + noOfTiles);
                
                for (let r = 1; r <= noOfTiles  ; r++) {
                    // const element = array[r];
                    var bgColor = r % 2 == 0 ? "red" : "green";
                    $("#area").append("<div id='tile_"+r+"' style='width:"+((inch * tileW))+"px; height:"+((inch * tileH))+"px; background-color: " + bgColor + "'' class='border_color'> </div>");
                    
                }
            });
        });
#area {
            border: 1px solid black;
            height: 25px;
            width: 25px;
            display: flex;
            flex-wrap: wrap;
        }
        .border_color{
            /* border: 1px solid black; */
            outline: 0px solid; /* use instead of border */
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Tile Width (inches): </p><input type="numbers" id ="tileWidth" placeholder="Tile Width" value="6">
    <p>Tile Height (inches): </p><input type="numbers" id ="tileHeight" placeholder="Tile Height" value="4">
    <br>
    <p>Area Width (foot): </p><input type="numbers" id ="areaWidth" placeholder="Area Width" value="11.5">
    <p>Area Height (foot): </p><input type="numbers" id ="areaHeight" placeholder="Area Height" value="6.5">
    <button id="btnCalculate" >Calculate</button>
        
    

    <div id="area">

    </div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...