Javascript 防止JQuery中动态创建的div重叠
我目前正在制作一个网页,其中一组可拖动的图像随着时间的推移出现在随机位置。我希望防止新创建的div重叠,并对出现的新div数量进行限制 下面是我的当前代码Javascript 防止JQuery中动态创建的div重叠,javascript,jquery,collision-detection,overlap,limits,Javascript,Jquery,Collision Detection,Overlap,Limits,我目前正在制作一个网页,其中一组可拖动的图像随着时间的推移出现在随机位置。我希望防止新创建的div重叠,并对出现的新div数量进行限制 下面是我的当前代码 var Images = ['https://material.io/icons/static/images/icons-180x180.png', 'https://iconscout.com/ms-icon-310x310.png', 'https://maxcdn.icons8.com/Share/icon/Food//cherry16
var Images = ['https://material.io/icons/static/images/icons-180x180.png', 'https://iconscout.com/ms-icon-310x310.png', 'https://maxcdn.icons8.com/Share/icon/Food//cherry1600.png', 'https://lh3.googleusercontent.com/Ax2wQYxjDITuZEpc6K9EDYPG7C839tb4PApia4Tmf18u8XehB-twqhVgDVPgxxExkr4=w300',
'https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-256.png',
'http://files.softicons.com/download/game-icons/super-mario-icons-by-sandro-pereira/ico/Mushroom%20-%201UP.ico'],
screenWidth,
screenHeight;
$(document).ready(function() {
screenWidth = $(window).width();
screenHeight = $(window).height();
$(window).on('resize', function(){
screenWidth = $(window).width();
screenHeight = $(window).height();
})
setInterval(function () {
var x = Math.random() * screenWidth,
y = Math.random() * screenHeight;
addDiv(x, y);
}, 2000);
});
function addDiv(x,y) {
var randImageIndex = Math.floor( (Math.random() * (Images.length - 1) ) );
var Image = Images[randImageIndex];
var newDiv = $('<div class="object"><img src=' + Image + ' height="100" width="100"></div>').css({top:x,left:y});
$('body').append(newDiv);
newDiv.draggable();
newDiv.on('click', function() {
$(this).remove();
})
}
var图像=[]https://material.io/icons/static/images/icons-180x180.png', 'https://iconscout.com/ms-icon-310x310.png', 'https://maxcdn.icons8.com/Share/icon/Food//cherry1600.png', 'https://lh3.googleusercontent.com/Ax2wQYxjDITuZEpc6K9EDYPG7C839tb4PApia4Tmf18u8XehB-twqhVgDVPgxxExkr4=w300',
'https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-256.png',
'http://files.softicons.com/download/game-icons/super-mario-icons-by-sandro-pereira/ico/Mushroom%20-%201UP.ico'],
屏幕宽度,
屏幕高度;
$(文档).ready(函数(){
屏幕宽度=$(窗口).width();
屏幕高度=$(窗口).height();
$(窗口).on('resize',function()){
屏幕宽度=$(窗口).width();
屏幕高度=$(窗口).height();
})
setInterval(函数(){
var x=Math.random()*屏幕宽度,
y=Math.random()*屏幕高度;
addDiv(x,y);
}, 2000);
});
函数addDiv(x,y){
var randImageIndex=Math.floor((Math.random()*(Images.length-1));
var Image=图像[randImageIndex];
var newDiv=$('').css({top:x,left:y});
$('body').append(newDiv);
newDiv.draggable();
newDiv.on('click',function(){
$(this.remove();
})
}
如有任何建议,将不胜感激