jQuery随机顶/左定位前DOM [英] jQuery Random Top/Left positioning pre-DOM

查看:136
本文介绍了jQuery随机顶/左定位前DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图随机的顶部/左边定位随机数的元素(跨度),将至少50像素远离彼此,以确保一个干净的分散。现在的代码如下:

I'm trying to get random top/left positioning for a random number of elements (spans) that will be at least 50 pixels away from each-other to ensure a clean scatter. The code I have right now follows:

function PositionOK(x, y) {
    axisarray.sort(function (a, b) {
        return a - b
    });
    for (var i in axisarray) {
        var pos = axisarray[i];
        if (Math.abs(x - pos.x) < 50) {
            return false;
        }
        if (Math.abs(y - pos.y) < 50) {
            return false;
        }
    }
    return true;
}
for (var xy = 0; xy < termArray.length * 2; xy++) {
    var x = Math.floor(Math.random() * 500);
    var y = Math.floor(Math.random() * 800);
    if (PositionOK(x, y)) {
        axisarray.push({
            'xaxis': x,
            'yaxis': y
        });
    } else axisarray.push({
        'xaxis': x + 50,
        'yaxis': y + 50
    });
}

示例输出:

Sample output:

正如你所看到的,它们不是均匀分布的。有些是浮动在另一个之上,当他们应该分布至少50px。
任何建议/解决方案?

As you can see, they are not evenly distributed. Some are floating above another, when they should be spread out at least 50px. Any advice/solutions?

推荐答案

基于顺序的解决方案(最多支持12个术语,

Sequential based solution (up to 12 terms supported until I mess with the css)

axisarray = [];
var x, y;
x = y = 0;
for (var xy = 0; xy < termArray.length * 2; xy++) {
    function genxy() {
        if (xy % 3 == 0) {
            var temp = Math.floor((Math.random() * 100) + 60);
            y = axisarray[xy - 1].yaxis + temp;
            x = Math.floor((Math.random() * 125) + 100);
        } else {
            y = axisarray[xy - 1].yaxis;
            x = axisarray[xy - 1].xaxis + 300;
        }
    }
    if (xy > 0 && xy <= 12) {
        genxy();
    } else if (xy > 12) {
        x = Math.floor((Math.random() * 125) + 100);
        y = Math.floor((Math.random() * 100) + 75);
    } else {
        x = 100;
        y = 50;
    }
    if (xy == termArray.length * 2 - 1) axisarray.sort(function (a, b) {
        return a - b
    });
    axisarray.push({
        'xaxis': x,
        'yaxis': y
    });
}

这篇关于jQuery随机顶/左定位前DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆