Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Заполнение div-а div-оми по условию. (https://javascript.ru/forum/jquery/65495-zapolnenie-div-div-omi-po-usloviyu.html)

Black_Star 22.10.2016 10:26

Заполнение div-а div-оми по условию.
 
Бодрый пень уважаемые. Возник интересен в реализации фичи по заполнению одного большого дива, дивами поменьше при условии того что б их сумарная величина размеров не была больше за величину большого дива.
Приведу код
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div id="square">
			<div id="minSquare">
				<div id="first">
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
			
				</div>
			</div>
		</div>

#square {
		width: 600px;
		height: 600px;
		border: 1px solid black;	

}

#minSquare {
	position: relative;
	margin: 5%;
	width: 500px;
	height: 500px;
	border: 1px solid black;
	background-color: yellow;
	/*overflow: hidden;*/
		
}

#first {
	position: absolute;
	height: 100%;
	width: 500px;
	margin-top: -2%;
	z-index: 1;

}

#second {
	position: absolute;
	height: 100%;
	width: 500px;
	margin-left: 4%;
	
	z-index: 2;

	perspective: 200px;
}
.one {
	width: 5%;
	height: 5%;
	background-color: red;
	border: 1px solid black;
	


.one:hover {
  	/*perspective: 100px;*/
	transform-origin: right; 
	transition: transform 0.5s;
	transform: rotateY(60deg);
	background-color: white;
}


window.onload = function() {

		$(function() {

				$('#minSquare').append('<div id="second">')

				$('#second').css({'width': '100%', 'height': '100%'});

				var widthOne = $('.one').width();
				var heightOne = $('.one').height();
				console.log('width of One block =' + widthOne);
				console.log('heigh of One block =' + heightOne);

				var rowWidth = $('#second').width();
				var rowHeight = $('#second').height();

				console.log('all Long #second = ' + rowHeight);

				var full_height = $('.one').outerHeight();
				;

				while (rowHeight > full_height) {

						$("#second > div ").each(function () {

								full_height = $(this).height() + full_height;
						});

						$('#second').append('<div class="one">')

						console.log('sum all Height div-es =' + full_height);

				}

		})
			
}

Я не понимаю почему мой цикл отрисовывает только 7 div-ов хотя по логике должен чуть меньше 20 при данных значениях w/h у класса One. подскажите пожалуйста где я туплю.

И ещё вопрос - как этими красными квадратиками заполнить пространство по горизонтале ?

рони 22.10.2016 10:34

Black_Star,
делайте пример целиком, а не часьтями и c run

рони 22.10.2016 10:45

Black_Star,
строка 26 удваивает предыдущий результат, each ненужен

Black_Star 22.10.2016 10:47

Цитата:

Сообщение от рони
делайте пример целиком, а не часьтями и c run

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Squama</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style type="text/css">
	#square {
		width: 600px;
		height: 600px;
		border: 1px solid black;	

}

#minSquare {
	position: relative;
	margin: 5%;
	width: 500px;
	height: 500px;
	border: 1px solid black;
	background-color: yellow;
	/*overflow: hidden;*/
		
}

#first {
	position: absolute;
	height: 100%;
	width: 500px;
	margin-top: -2%;
	z-index: 1;

}

#second {
	position: absolute;
	height: 100%;
	width: 500px;
	margin-left: 4%;
	
	z-index: 2;

	perspective: 200px;
}

.one {
	
	width: 5%;
	height: 5%;
	background-color: red;
	border: 1px solid black;
	}

.one:hover {
	
	 /*  */
  	/*perspective: 100px;*/
	transform-origin: right; 
	transition: transform 0.5s;
	transform: rotateY(60deg);
	background-color: white;
}



</style>	
</head>
<body>
		<div id="square">
			<div id="minSquare">
				<div id="first">
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
					<div class="one"></div>
			
				</div>


			



			</div>
		</div>
<script type="text/javascript">
	window.onload = function() {

		$(function() {

				$('#minSquare').append('<div id="second">')

				$('#second').css({'width': '100%', 'height': '100%'});

				var widthOne = $('.one').width();
				var heightOne = $('.one').height();
				console.log('width of One block =' + widthOne);
				console.log('heigh of One block =' + heightOne);

				var rowWidth = $('#second').width();
				var rowHeight = $('#second').height();

				console.log('all Long #second = ' + rowHeight);

				var full_height = $('.one').outerHeight();
				;

				while (rowHeight > full_height) {

						$("#second > div ").each(function () {

								full_height = $(this).height() + full_height;
						});

						$('#second').append('<div class="one">')

						console.log('sum all Height div-es =' + full_height);

				}

		})
			
}


	
</script>
</body>

</html>

рони 22.10.2016 11:43

заполнить div блоками
 
Black_Star,
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
#square {
    width: 600px;
    height: 600px;
    border: 1px solid black;

  }

  #minSquare {
  position: relative;
  margin: 5%;
  width: 500px;
  height: 500px;
  border: 1px solid black;
  background-color: yellow;
  /*overflow: hidden;*/

  }

  #first {
  position: absolute;
  height: 100%;
  width: 500px;
  margin-top: -2%;
  z-index: 1;

  }

  #second {
  position: absolute;
  height: 100%;
  width: 500px;
  margin-left: 4%;

  z-index: 2;

  perspective: 200px;
  }
  .one {
  float: left;
  box-sizing:  border-box;
  width: 5%;
  height: 5%;
  background-color: red;
  border: 1px solid black;
  }


  .one:hover {
    /*perspective: 100px;*/
  transform-origin: right;
  transition: transform 0.5s;
  transform: rotateY(60deg);
  background-color: white;
  }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
  <script>
    $(function() {
        var div = $('#minSquare');
        var rowWidth = div.width();
        var rowHeight = div.height();
        var one = $('<div>',{'class' : 'one'}).appendTo(div);
        var widthOne = one.outerWidth(true);
        var heightOne = one.outerHeight(true);
        var len = (rowHeight/heightOne|0) * (rowWidth/widthOne|0)-1;
        for (var i=0; i<len; i++)  {
          div.append(one.clone())
        }
        })
  </script>
</head>

<body>
  <div id="square">
    <div id="minSquare"></div>
  </div>
</body>
</html>

рони 22.10.2016 11:44

Black_Star,
пост 4 строка 124
full_height = 0;

Black_Star 22.10.2016 12:08

Цитата:

Сообщение от рони
full_height = 0;

Не понял, к чему это ? console.log('full_height = ' + full_height);
// full_height == 27

рони 22.10.2016 12:11

Цитата:

Сообщение от Black_Star
Не понял, к чему это ?

попытайтесь понять или проверить хотябы что изменится

Black_Star 22.10.2016 12:26

Цитата:

Сообщение от рони
попытайтесь понять или проверить хотябы что изменится

Эмм, я проверил. При замене var full_height = 0; ни чего не поменялось, выводит всё те же 7 блоков. Я не понял почему? Оно не понимает % соотношение сторон ?

Да и Ваша запись var len = (rowHeight/heightOne|0) * (rowWidth/widthOne|0)-1;
Тоже мне не понятна. Вы берете площадь размеров большого дива W*H делите на площадь маленького дива w*h узнаете количество возможно вмещаемых маленьких блоков и отнимаете 1. Но что-то в наглядном примере 500px / приблизительно 25px * 500px / приблизительно 25px -1 = 399 блоков и тоже всё пространство не заполнено

рони 22.10.2016 12:52

Цитата:

Сообщение от Black_Star
тоже всё пространство не заполнено

в примере всё заполнено или нет? пост №7

Цитата:

Сообщение от Black_Star
При замене var full_height = 0; ни чего не поменялось, выводит всё те же 7 блоков.

ой!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Squama</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style type="text/css">
  #square {
    width: 600px;
    height: 600px;
    border: 1px solid black;

}

#minSquare {
  position: relative;
  margin: 5%;
  width: 500px;
  height: 500px;
  border: 1px solid black;
  background-color: yellow;
  /*overflow: hidden;*/

}

#first {
  position: absolute;
  height: 100%;
  width: 500px;
  margin-top: -2%;
  z-index: 1;

}

#second {
  position: absolute;
  height: 100%;
  width: 500px;
  margin-left: 4%;

  z-index: 2;

  perspective: 200px;
}

.one {

  width: 5%;
  height: 5%;
  background-color: red;
  border: 1px solid black;
  }

.one:hover {

   /*  */
  	/*perspective: 100px;*/
  transform-origin: right;
  transition: transform 0.5s;
  transform: rotateY(60deg);
  background-color: white;
}



</style>
</head>
<body>
    <div id="square">
      <div id="minSquare">
        <div id="first">
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>

        </div>






      </div>
    </div>
<script type="text/javascript">
  window.onload = function() {

    $(function() {

        $('#minSquare').append('<div id="second">')

        $('#second').css({'width': '100%', 'height': '100%'});

        var widthOne = $('.one').width();
        var heightOne = $('.one').height();
        console.log('width of One block =' + widthOne);
        console.log('heigh of One block =' + heightOne);

        var rowWidth = $('#second').width();
        var rowHeight = $('#second').height();

        console.log('all Long #second = ' + rowHeight);

        var full_height = $('.one').outerHeight();
        ;

        while (rowHeight > full_height) {
            full_height = 0;
            $("#second > div ").each(function () {

                full_height = $(this).height() + full_height;
            });

            $('#second').append('<div class="one">')

            console.log('sum all Height div-es =' + full_height);

        }

    })

}



</script>
</body>

</html>

Black_Star 22.10.2016 13:02

Цитата:

Сообщение от рони
тоже всё пространство не заполнено
в примере всё заполнено или нет? пост №7

Если Вы имели ввиду Ваш пост №5 то там тоже не всё заполнено

Новый Ваш пример работает болие правильно. Но всё равно, оно выводит 21 блок, хотя по идее если большой блок 500х500px а маленький 25х25px (5% х 5%) то по логике while (rowHeight > full_height) оно должно б было вывести 20 или даже 19 блоков. (Что в принципе видно визуально)

рони 22.10.2016 13:27

Цитата:

Сообщение от Black_Star
Если Вы имели ввиду Ваш пост №5 то там тоже не всё заполнено

в каком браузере???
Цитата:

Сообщение от Black_Star
маленький 25х25px

это ваши предположения -- смотрите пост 5
вставить фото кнопка

Black_Star 22.10.2016 13:42

Цитата:

Сообщение от рони
в каком браузере???

Chrom Версия 53.0.2785.143 m (64-bit)
Ну я и в других просмотрел, В ФФ и Опере видно нормально. Заполняет всё как надо, а в Хроме чё-то недозаполняет.
А вот последний пост прогнал по всем своим браузерам, так там во всех одно и тоже 21 блок


рони 22.10.2016 14:49

Black_Star,
более помочь ничем не могу, в моих браузерах пост 5 работает нормально выводит 400 маленьких блоков.
21 блок выводит ваш код, потому что условие и размеры неправильно считаются.
строка 47 и строки 117 -123 ... медитируйте
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Squama</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<style type="text/css">
  #square {
    width: 600px;
    height: 600px;
    border: 1px solid black;

}

#minSquare {
  position: relative;
  margin: 5%;
  width: 500px;
  height: 500px;
  border: 1px solid black;
  background-color: yellow;
  /*overflow: hidden;*/

}

#first {
  position: absolute;
  height: 100%;
  width: 500px;
  margin-top: -2%;
  z-index: 1;

}

#second {
  position: absolute;
  height: 100%;
  width: 500px;
  margin-left: 4%;

  z-index: 2;

  perspective: 200px;
}

.one {
  box-sizing: border-box;
  width: 5%;
  height: 5%;
  background-color: red;
  border: 1px solid black;
  }

.one:hover {

   /*  */
  	/*perspective: 100px;*/
  transform-origin: right;
  transition: transform 0.5s;
  transform: rotateY(60deg);
  background-color: white;
}



</style>
</head>
<body>
    <div id="square">
      <div id="minSquare">
        <div id="first">
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>
          <div class="one"></div>

        </div>






      </div>
    </div>
<script type="text/javascript">
window.onload = function() {
    $(function() {
        $("#minSquare").append('<div id="second">');
        $("#second").css({
            "width": "100%",
            "height": "100%"
        });
        var widthOne = $(".one").width();
        var heightOne = $(".one").height();
        console.log("width of One block =" + widthOne);
        console.log("heigh of One block =" + heightOne);
        var rowWidth = $("#second").width();
        var rowHeight = $("#second").height();
        console.log("all Long #second = " + rowHeight);
        var full_height = $(".one").outerHeight();
        while (rowHeight > full_height) {
            $("#second").append('<div class="one">');
            full_height = 0;
            $("#second > div ").each(function() {
                full_height += this.offsetHeight
            })
        }
    })
};
</script>
</body>

</html>

Black_Star 23.10.2016 08:47

Цитата:

Сообщение от рони
более помочь ничем не могу, в моих браузерах пост 5 работает нормально выводит 400 маленьких блоков.
21 блок выводит ваш код, потому что условие и размеры неправильно считаются.
строка 47 и строки 117 -123 ... медитируйте

Да, спасибо. Ваш код работает идеально. Отображает как раз 20 блоков.
Ещё вопрос по горизонтальному заполнению.

Как сделать что б генерируемый код выглядел так:
<div id="square">
<div id="minSquare">
<div class="column">
<div class="one"></div>
<div class="one"></div>
<div class="one"></div>
<div class="one"></div>
<div class="one"></div>
++++ И так далие, пока сумма heigh div-s class="one" < Heigh div id="minSquare" +++
</div>
<div id="column">

~ div-s class="one"~
</div> Количество дивов <div id="column"> с потомками "one" должно быть столько что б они перекрывали по ширине div id="minSquare"
</div>
</div>
Выглядеть приблизительно так. Единственное что перекрытие у каждого нового <div id="column"> z-index +1
Тут у меня проблема возникла в том что у меня class="column" имеет
.column {
position: absolute;
height: 100%;
width: 100%;
}

и каждый новый столбец должен иметь смещение по горизонтале а каждый парный ещё и по вертикале

var newZindex = 1; // каждый новый столбец перекрывает предыдущий
var newMarginLeft = 4; // смещение каждого столбца вправо на 4%
var newMarginTop = -2; // каждый парный div с классом colomn должен подниматься вверх на -2%;


$('.column').css({
"margin-left" : "newMarginLeft" * i + "%" ,
"margin-top" : "newMarginTop" * i + "%" , // тут у меня вопрос как проверять на четность. Думал как-то привязать к z-index
"z-index" : "newZindex" * i
});

Ещё вопрос как сделать проверку на то что б сумма ширины всех колонок с классом .column была меньше ширины div id="minSquare", была мысль как Вы сделать var len = (rowWidth/widthOne|0);
for (var i=0; i<len; i++) но тут такое не прокатит, я ведь пишу .column {width: 100%;}, да и абсолютное позиционирование + они на разных уровнях z-index .вообщем Одни вопросы.

рони 23.10.2016 09:28

Black_Star,
пас ... вам к специалисту по css

рони 23.10.2016 09:43

Black_Star,
на последок ... :)
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
#square {
    width: 600px;
    height: 600px;
    border: 1px solid black;

  }

  #minSquare {
  position: relative;
  margin: 5%;
  width: 500px;
  height: 500px;
  border: 1px solid black;
  background-color: yellow;
  /*overflow: hidden;*/
  display: flex;
   flex-wrap:  wrap;

  }


  .one {
  float: left;
  box-sizing:  border-box;
  width: 5%;
  height: 5%;
  background-color: red;
  border: 1px solid black;
  }
  .one:nth-child(2n) {
   margin-top: -4px;
   z-index: 10;
   margin-left: -2px;
  }


  .one:hover {
    /*perspective: 100px;*/
  transform-origin: right;
  transition: transform 0.5s;
  transform: rotateY(60deg);
  background-color: white;
  }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
  <script>
    $(function() {
        var div = $('#minSquare');
        var rowWidth = div.width();
        var rowHeight = div.height();
        var one = $('<div>',{'class' : 'one'}).appendTo(div);
        var widthOne = one.outerWidth(true);
        var heightOne = one.outerHeight(true);
        var len = (rowHeight/heightOne|0) * (rowWidth/widthOne|0)-1;
        for (var i=0; i<len; i++)  {
          div.append(one.clone())
        }
        })
  </script>
</head>

<body>
  <div id="square">
    <div id="minSquare"></div>
  </div>
</body>
</html>

Black_Star 26.10.2016 14:32

Спасибо за помощь. Вот что на выходи вышло :)
https://codepen.io/BlackStar1991/pen/JRVRYm


Часовой пояс GMT +3, время: 09:11.