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

Man*_*ish 5 javascript css jquery

我想在随机位置的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 = $('<div/>').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));
    }
})();
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Vik*_*ukh 3

你已经弄清楚了大部分内容。您只需将.containerdiv 视为网格即可避免任何重叠或外围项目。

看看这个小提琴

代码如下所示:

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 = $('<div/>').addClass("tile");
    $newdiv.css({
        'position':'absolute',
        'left':(xpos[i] * tilesize)+'px',
        'top':(ypos[i] * tilesize)+'px'
    }).appendTo( '.container' ).html(d);  
});
Run Code Online (Sandbox Code Playgroud)

PS:我在小提琴中使用了下划线以使事情变得更容易,因为我个人讨厌编写for循环。