在随机位置的侧div中生成数字而不重叠

我想在随机位置的div内显示随机数而不重叠。 我可以在随机位置显示随机数,但它会在框外显示并相互重叠。

这是我的代码:

JS小提琴

var width = $('.container').innerWidth(); var height = $('.container').innerHeight(); (function generate() { // vary size for fun for (i = 0; i < 15; i++) { var divsize = 12; var color = '#' + Math.round(0xffffff * Math.random()).toString(16); $newdiv = $('
').css({ 'width': divsize + 'px', 'height': divsize + 'px' }); // make position sensitive to size and document's width var posx = (Math.random() * (width - divsize)).toFixed(); var posy = (Math.random() * (height - divsize)).toFixed(); $newdiv.css({ 'position': 'absolute', 'left': posx + 'px', 'top': posy + 'px', 'float': 'left' }).appendTo('.container').html(Math.floor(Math.random() * 9)); } })();

我怎样才能做到这一点?

你已经弄清楚了大部分问题。 您只需要将.container div视为网格,以避免任何重叠或外围项目。

看看这个小提琴

这是代码的样子:

 var tilesize = 18, tilecount = 15; var gRows = Math.floor($(".container").innerWidth()/tilesize); var gCols = Math.floor($('.container').innerHeight()/tilesize); var vals = _.shuffle(_.range(tilecount)); var xpos = _.shuffle(_.range(gRows)); var ypos = _.shuffle(_.range(gCols)); _.each(vals, function(d,i){ var $newdiv = $('
').addClass("tile"); $newdiv.css({ 'position':'absolute', 'left':(xpos[i] * tilesize)+'px', 'top':(ypos[i] * tilesize)+'px' }).appendTo( '.container' ).html(d); });

PS:我在我的小提琴中使用了下划线让我更容易,因为我个人讨厌写作循环。

如果你需要创建的div的数量足够小(即你没有冒险他们不适合),那么一个简单的算法是:

  • 选择一个随机位置(x0, y0)-(x1, y1)
  • 检查以前选择的任何矩形是否重叠
  • 如果没有重叠,则添加rect,否则循环返回并选择另一个随机位置

在代码中

 var selected = []; for (var i=0; i= selected[i].x1 || y0 >= selected[i].y1 || x1 <= selected[i].x0 || y1 <= selected[i].y0)) { i++; } if (i == selected.length) { // Spot is safe, add it to the selection selected.push({x0:x0, y0:y0, x1:x1, y1:y1}); break; } // The choice collided with a previously added div // just remain in the loop so a new attempt is done } } 

如果元素很多,并且可以放置n-1 ,这样就没有放置第n个元素的位置,那么事情要复杂得多。

对于这个问题的一维版本的解决方案,请参阅此答案 。

您可以添加每个数字的数组位置。 然后,当你为数字生成新位置时,你应该检查数组中是否有posx posy,如果有错误的位置数,那么如果为true则生成新的posx和posy