gpt4 book ai didi

jquery - 随机定位多个图像

转载 作者:行者123 更新时间:2023-12-01 02:40:56 26 4
gpt4 key购买 nike

我正在使用这个简单的脚本,它将在页面上随机放置.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);

});

最佳答案

你可以试试这个:

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

关于jquery - 随机定位多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com