2016-04-28 99 views
2

我正在使用这个简单的脚本,它将在页面上随机放置一个类为.random的图像 - 效果很好。试图找出一种方法将这个应用于页面上的多个图像使用一个类,以便图像散布在页面上 - 现在如果它应用于多个图像,他们都使用相同的随机定位。随机位置多个图像

 $(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

如果您使用选择'$( '随机')'这将适用于这样的类中的所有图像(即你所有的图像) - 可能你想遍历列表,并将位置分别应用到每个图像 – ochi

回答

2

您可以使用jQuery each遍历您的选择器匹配。例如:

$(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

谢谢! “.each”完美地工作。 – adamo

+0

不客气:) –

+0

如果在身体中没有其他内容,则可能需要在CSS中指定高度(否则对于Y坐标,您将始终得到零) - 'body {height:500px; }' – ochi

4

你可以试试这个:

$(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

谢谢!与上述类似的酷解决方案也很有用。 – adamo

+0

@adamo很高兴我们可以帮助:) – ochi