2016-04-28 10 views
2

Ich verwende dieses einfache Skript, das ein Bild mit der Klasse .random auf der Seite nach dem Zufallsprinzip platziert - funktioniert super. Versuchen, eine Möglichkeit zu finden, dies auf mehrere Bilder auf der Seite mit einer einzigen Klasse anzuwenden, so dass die Bilder über die Seite verstreut sind - gerade jetzt, wenn sie auf mehr als ein Bild angewendet wird, verwenden sie alle die gleiche zufällige Positionierung.Zufallsposition Mehrere Bilder

 $(document).ready(function() { 
      var bodyWidth = document.body.clientWidth 
      var bodyHeight = document.body.clientHeight; 
      var randPosX = Math.floor((Math.random()*bodyWidth)); 
      var randPosY = Math.floor((Math.random()*bodyHeight)); 

      $('.random').css('left', randPosX); 
      $('.random').css('top', randPosY); 

     }); 
+0

wenn Sie die Wähler '$ ('random')' es auf alle Bilder mit dieser Klasse gelten (dh alle Ihre Bilder) - wahrscheinlich möchten Sie die Liste durchlaufen und die Positionen auf jeden einzeln anwenden – ochi

Antwort

2

Sie jQuery each können durch Ihre Wähler Spiele iterieren. Beispiel:

$(document).ready(function() { 
    var bodyWidth = document.body.clientWidth 
    var bodyHeight = document.body.clientHeight; 
    $('.random').each(function() { 
     var randPosX = Math.floor((Math.random() * bodyWidth)); 
     var randPosY = Math.floor((Math.random() * bodyHeight)); 
     $(this).css('left', randPosX); 
     $(this).css('top', randPosY); 
     posLog.innerHTML = posXY 
    }); 
}); 
+0

Vielen Dank !!! ".each" hat perfekt funktioniert. – adamo

+0

Gern geschehen :) –

+0

Wenn es im Körper keine anderen Inhalte gibt, müssen Sie möglicherweise eine Höhe im CSS angeben (sonst erhalten Sie immer Null für die Y-Koordinate) - 'body { height: 500px; } ' – ochi

4

Sie konnten dieses versuchen:

$(document).ready(function() { 
 
    var bodyWidth = document.body.clientWidth 
 
    var bodyHeight = document.body.clientHeight; 
 

 
    $('.random').each(function(idx, img) { 
 
    var randPosX = Math.floor((Math.random() * bodyWidth)); 
 
    var randPosY = Math.floor((Math.random() * bodyHeight)); 
 
    console.log(randPosY); 
 
    $(img).css('left', randPosX); 
 
    $(img).css('top', randPosY); 
 

 
    }); 
 
});
body { 
 
    height: 500px; 
 
} 
 
.random { 
 
    position: absolute; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 

 
<img class="random" src="http://lorempixel.com/200/200/"> 
 
<img class="random" src="http://lorempixel.com/200/200/"> 
 
<img class="random" src="http://lorempixel.com/200/200/"> 
 
<img class="random" src="http://lorempixel.com/200/200/"> 
 
<img class="random" src="http://lorempixel.com/200/200/">

+0

Danke! Coole Lösung, ähnlich der oben genannten, funktioniert auch gut. – adamo

+0

@adamo froh, wir könnten helfen :) – ochi