Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 随机定位多幅图像_Jquery - Fatal编程技术网

Jquery 随机定位多幅图像

Jquery 随机定位多幅图像,jquery,Jquery,我正在使用这个简单的脚本,它将在页面上随机放置一个带有类.random的图像,效果非常好。试图找到一种方法,使用单个类将其应用于页面上的多个图像,这样图像就会分散在页面上——现在,如果应用于多个图像,它们都使用相同的随机定位 $( document ).ready(function() { var bodyWidth = document.body.clientWidth var bodyHeight = document.body.cli

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

        });

您可以使用jQuery
每个
来迭代选择器匹配。例如:

$(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
    });
});
你可以试试这个:

$(文档).ready(函数(){
var bodyWidth=document.body.clientWidth
var bodyHeight=document.body.clientHeight;
$('.random')。每个(函数(idx、img){
var randPosX=Math.floor((Math.random()*bodyWidth));
var randPosY=Math.floor((Math.random()*车身高度));
console.log(randPosY);
$(img).css('left',randPosX);
$(img).css('top',randPosY);
});
});
正文{
高度:500px;
}
.随机的{
位置:绝对位置;
}


如果您使用选择器
$('.random')
它将应用于具有此类类别的所有图像(即您的所有图像)-可能您希望循环浏览列表并将位置应用于每个图像谢谢!很酷的解决方案,类似于上面的解决方案,也很有效。@adamo很高兴我们能提供帮助:)如果正文中没有其他内容,您可能需要在CSS中指定一个高度(否则Y坐标将始终为零)
body{height:500px;}