在随机位置生成边div中的数字,不重叠 [英] Generate numbers in side div at random position without overlapping
本文介绍了在随机位置生成边div中的数字,不重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在随机位置的div中显示随机数,而不重叠。
我可以在随机位置显示随机数,但它在框外并且彼此重叠。
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 and overlapping each other.
这是我的代码:
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));
}
})();
我该如何做?
推荐答案
你有大部分的想法。您只需要将 .container
div视为网格,以避免任何重叠或外围项目。
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.
请查看 此小提琴 。
代码如下:
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);
});
PS:我在小提琴上用下划线使事情对我更容易, for
循环。
这篇关于在随机位置生成边div中的数字,不重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文