Generate numbers in side div at random position without overlapping

前端 未结 3 1141
孤城傲影
孤城傲影 2021-01-18 10:00

I want to display random numbers inside a div at random positions without overlapping. I am able to display random number at random position but its going outside the box an

3条回答
  •  粉色の甜心
    2021-01-18 10:37

    You've got most of it figured out. You just need to think of the .container div as a grid to avoid any overlap or outlying items.

    Just check out this fiddle.

    Here's what the code looks like:

    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:I have used underscore in my fiddle to make things easier for me and because I personally hate writing for loops.

提交回复
热议问题