2016-04-24 10 views
0

Ich versuche, divs in zufälligen Positionen mit der Breite und Höhe der Seite anzuhängen, es funktioniert, aber die Divs sind wirklich weit unten auf der Seite oder auf der linken Seite platziert. Ich habe screen.width, screen.availWidth und document.body.clientWidth verwendet und ich kann es nicht herausfinden. Ich denke es liegt teilweise an der Positionierung des Divs.behalten angehängte relative Elemente im Körper

Heres mein Code

$(document).ready(function() { 
 
\t var i = 1; 
 
\t function createDiv() { 
 
\t \t setTimeout(function() { 
 
\t \t \t var $newDiv = $('<div></div>').css({ 
 
\t \t \t \t "position": "relative", 
 
\t \t \t \t "width": "100px", 
 
\t \t \t \t "height": "100px", 
 
\t \t \t \t "background-color": "#ccbfd9", 
 
\t \t \t \t "border-radius": "720px" 
 
\t \t \t }); 
 
\t \t \t $($newDiv).each(function() { 
 
\t \t \t // document.body.clientHeight 
 
\t \t \t \t var leftRandPos = Math.floor((Math.random() * window.innerWidth)); 
 
\t \t var topRandPos = Math.floor((Math.random() * window.innerHeight)); 
 
\t \t \t \t $(this).css('left', leftRandPos); 
 
\t \t \t \t $(this).css('top', topRandPos); 
 
\t \t \t \t $('body').append($newDiv); 
 
\t \t \t }); 
 
\t \t \t i++; 
 
\t \t \t if (i < 100) { 
 
\t \t \t \t createDiv(); 
 
\t \t \t } 
 
\t \t }, 250); 
 
\t } 
 
\t createDiv(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Irgendwelche Vorschläge?

+0

position: absolute sollte sie nehmen, wo Sie wollen. – user6245342

+0

danke es sieht jetzt wirklich cool aus – Swift

Antwort

0

Absolute Position ist, was Sie suchen.

position: absolute; 
top: some px; 
left: some px; 

Um im Zentrum der Seite (nur zum Spaß) zu erhalten:

top: 50%; 
left: 50px; 
margin-left: -50px; //half of it's width 
margin-top: -50px; //half of it's height 
+0

verdammt. habe den Kommentar nicht gesehen. Naja. zumindest hat die Frage eine Antwort. : D –

Verwandte Themen