Tengo una función que crea divs con un círculo.
Ahora todos están creados y aparecen al principio de la página y van más allá en orden.
Luego, necesito que cada círculo aparezca en un lugar aleatorio. Hice esto pero solo hay un problema.
Cuando el círculo aparece en el borde de la página, se expande y aparece el desplazamiento
¿Cómo puedo limitar esto para que los círculos no se salgan del borde de la página?
function createDiv(id, color) { let div = document.createElement('div'); var currentTop = 0; var documentHeight = document.documentElement.clientHeight; var documentWidth = document.documentElement.clientWidth; div.setAttribute('class', id); if (color === undefined) { let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547']; div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]; } else { div.style.backgroundColor = color; } div.classList.add("circle"); div.classList.add("animation"); currentTop = Math.floor(Math.random() * documentHeight) + 1; currentLeft = Math.floor(Math.random() * documentWidth) + 1; div.style.top = currentTop + "px"; div.style.left = currentLeft + "px"; document.body.appendChild(div); } let i = 0; const oneSecond = 1000; setInterval(() => { i += 1; createDiv(`circle${i}`) }, oneSecond); .circle { clip-path: circle(50%); height: 40px; width: 40px; margin: 20px; position: absolute; }Creo que se debe a 2 cosas:
Mira aquí mi versión, si tienes alguna duda intentaré ser más clara :)
var widthHeight = 40; // <-- circle width var margin = 20; // <-- margin - is it necessary ? var delta = widthHeight + margin; function createDiv(id, color) { let div = document.createElement('div'); var currentTop = 0; var documentHeight = document.documentElement.clientHeight; var documentWidth = document.documentElement.clientWidth; div.setAttribute('class', id); if (color === undefined) { let colors = ['#35def2', '#35f242', '#b2f235', '#f2ad35', '#f24735', '#3554f2', '#8535f2', '#eb35f2', '#f2359b', '#f23547']; div.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]; } else { div.style.backgroundColor = color; } div.classList.add("circle"); div.classList.add("animation"); // Get the random positions minus the delta currentTop = Math.floor(Math.random() * documentHeight) - delta; currentLeft = Math.floor(Math.random() * documentWidth) - delta; // Keep the positions between -20px and the current positions var limitedTop = Math.max(margin * -1, currentTop); var limitedLeft = Math.max(margin * -1, currentLeft); div.style.top = limitedTop + "px"; div.style.left = limitedLeft + "px"; document.body.appendChild(div); } let i = 0; const oneSecond = 1000; setInterval(() => { i += 1; createDiv(`circle${i}`) }, oneSecond); .circle { clip-path: circle(50%); height: 40px; width: 40px; margin: 20px; position: absolute; }