Как рандомно расположить эти div, если они рапологаються друг под другом?

var x = Math.floor(Math.random() * 1200)
var y = Math.floor(Math.random() * 1000)

$(window).click(function() {
  for (i = 0; i < 100; i++) {
    var div = document.createElement("div")
    $("div").css({
      "display": "block",
      "position": "relative",
      "left": x + "px",
      "top": y + "px",
      "width": "100px",
      "height": "60px",
      "background": "grey"
    });
    $("body").append(div);
  }
});

мне нужно создать 100 div в рандомном расположении на вкладке браузера.


Ответы (1 шт):

Автор решения: CbIPoK2513

Вариант на jQuery.

for (let i = 0; i < 100; i++) {
  let x = Math.floor(Math.random() * 1200),
    y = Math.floor(Math.random() * 1000),
    div = $('<div class="div"></div>').css({
      "left": x+"px",
      "top": y+"px"
    });
  $("body").append(div);
}
body .div {
  display: block;
  width: 100px;
  height: 100px;
  background: gray;
  position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Вариант с генерацией "внутри" экрана.

let w = $(window).width(),
    h = $(window).height();

for (let i = 0; i < 100; i++) {
  let x = Math.floor(Math.random() * w - 1),
      y = Math.floor(Math.random() * h - 1),
      r = Math.floor(Math.random() * 255),
      g = Math.floor(Math.random() * 255),
      b = Math.floor(Math.random() * 255),
      div;
    
  x = x - 50;
  y = y - 50;
    
  div = $('<div class="div"></div>').css({
      "left": x+"px",
      "top": y+"px",
      "background": `rgba(${r},${g},${b},.5)`
    });
  $("body").append(div);
}
body {
  margin: 0;
  overflow: hidden;
}

.div {
  display: block;
  width: 100px;
  height: 100px;
  background: gray;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Предложение от @OPTIMUS PRIME

let w = $(window).width(),
    h = $(window).height();

for (let i = 0; i < 100; i++) {
  let x = Math.floor(Math.random() * w - 1),
      y = Math.floor(Math.random() * h - 1),
      r = Math.floor(Math.random() * 90),
      z = Math.floor(Math.random() * 10),
      div;
    
  x = x - 50;
  y = y - 50;
    
  div = $('<div class="div"></div>').css({
      "left": x+"px",
      "top": y+"px",
      "transform": "rotate("+r+"deg)",
      "z-index": z
    });
  $("body").append(div);
}
body {
  margin: 0;
  overflow: hidden;
}

.div {
  display: block;
  width: 100px;
  height: 100px;
  background: #fff;
  position: absolute;
  box-shadow: 1px 1px 5px rgba(0,0,0,.65);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

→ Ссылка