如何在页面上随机放置几个元素?

时间:2013-11-28 20:56:19

标签: javascript jquery html css random

我想用Javascript / jQuery在页面上随机放置一个类的几个元素。我的想法是为margin-top,margin-left和z-index生成随机值。问题是我需要生成负数和正数之间的值(例如从-150px到300px),我不明白如何使用我使用的代码:

$(".randomnumber").each(function () {
    var randomtop = Math.floor(Math.random() * 101);
    var randomleft = Math.floor(Math.random() * 101);
    var randomzindex = Math.floor(Math.random() * 101);
    $(this).css({
        "margin-top": randomtop,
        "margin-left": randomleft,
        "z-index": randomzindex
    });
});

http://jsfiddle.net/7JGqZ/651/

所以我遇到的问题:

  1. 不知道如何使用负值 - 例如我需要将上边距设置为-150px到300px。

  2. 小提琴中的元素有点奇怪,比如他们的位置不是随机的,或者他们彼此相连......

  3. 更新

    让它工作,但仍然不喜欢结果,我实际上希望元素随机放置,以便它们适合页面大小,我的意思是元素将被放置在整个页面上,而不是太远了页面的边缘。现在我有一个固定在页面中心的父元素(宽度和高度= 0,顶部和底部= 50%),我的想法是定位其子元素,生成顶部和左边距,如下所示:

    $(document).ready(function(){
        $(".mood-img").each(function () {
            var height = $(window).height();
            var halfheight = height/2;
            var margintop = halfheight-400;
            var width = $(window).width();
            var halfwidth = width/2;
            var marginleft = halfwidth-500;
            var randomtop = getRandomInt(halfheight, margintop);
            var randomleft = getRandomInt(halfwidth, marginleft);
            var randomzindex = getRandomInt(1, 30);
    
    
            $(this).css({
                "margin-top": randomtop,
                "margin-left": randomleft,
                "z-index": randomzindex
            });
        });
    
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1) + min);
        }
    });
    

    http://jsfiddle.net/7JGqZ/657/

1 个答案:

答案 0 :(得分:4)

对于#1,您可以生成0到450之间的随机数,然后减去150

$(".randomnumber").each(function () {
    var randomtop = Math.floor(Math.random() * 450 - 150);
    var randomleft = Math.floor(Math.random() * 450 - 150);
    var randomzindex = Math.floor(Math.random() * 450 - 150);
    $(this).css({
        "margin-top": randomtop,
        "margin-left": randomleft,
        "z-index": randomzindex
    });
});

Updated jsFiddle

如果您希望元素随机放置在整个屏幕上而不会重叠边缘,您可以使用以下代码:Demo(我也将其清理干净了)

对于#2,在编码方面没有真正的随机性。大多数random,如Math.random都是从时间推导出来的。 From Mozilla

  

返回[0,1]范围内的伪随机数 - 即0之间   (包括)和1(独家)。随机数发生器是种子   从当前时间开始,如在Java中。

javascript中的数字尽可能随机。 Google more information and alternates如果你不相信我

为了演示Math.random的工作情况,我编辑了项目以允许numElems设置的任意数量的元素。尝试几次,效果很好。 Demo here

修改

我还建议使用scrollHeightscrollWidth,而不是使用jQuery的width()height(),因为它更具包容性,从而提供更准确的{{1}值}