2

我有重叠的元素,我想防止这种情况发生。这是一张图片: http: //grab.by/cB7t

此外,这里是这些元素的 CSS:

.navigationItem {
    background: #808080;
    -webkit-border-radius: 360px;
    padding: 1.0em;
    text-decoration: none;
    color: #fff;
    position: absolute;
    -webkit-box-shadow: 0px 2px 5px #909090;
    font-weight: bold;
    text-shadow: 1px 1px 2px #707070;
    font-size: 1.0em;
}

它们在 HTML 中:

<a href="#" class="navigationItem" id="nav0">play</a>
<a href="#" class="navigationItem" id="nav1">register</a>
<a href="#" class="navigationItem" id="nav2">our blog</a>
<a href="#" class="navigationItem" id="nav4">contact us</a>
<a href="#" class="navigationItem" id="nav5">about us</a>
<a href="#" class="navigationItem" id="nav6">our rules</a>`

如您所见,我将它们用作使用 HTMLa标记的简单样式链接。它们的位置是绝对的原因是因为我正在使用 jQuery 移动它们:

function moveAll() {

    for(var i = 0; i < AMOUNT; i++) {
        var random = Math.random() * 500;
        $("#nav" + i).animate({"left": random + i + "px"}, "slow");
        $("#nav" + i).animate({"top": random + i + "px"}, "slow");
    }
}

但是,当它们移动时,它们有时会重叠,这很烦人。如何防止它们重叠?感谢你付出的努力。

4

2 回答 2

6

删除position:absolute将使它们并排呈现。

JSFiddle

但是,如果重点是将它们随机分散,那么您将必须跟踪定位的元素并在计算它们的位置时考虑到这一点。您应该保存每个链接的位置,并根据之前已经定位的链接计算每个下一个链接的位置。当您想要随机位置且不重叠时,根本没有其他方法。

最终的非重叠解决方案

这是非重叠功能的一个工作示例。如果您不希望您的链接甚至不接触,您应该在语句条件中更改<to<=>to 。>=if

相关代码

var positions = [];
$(".navigationItem").each(function(){
    var ctx = $(this);
    var dim = {
        width: ctx.outerWidth(),
        height: ctx.outerHeight()
    };
    var success = false;

    // repeat positioning until free space is found
    while (!success)
    {
        dim.left = parseInt(Math.random() * 300);
        dim.top = parseInt(Math.random() * 300);
        var success = true;

        // check overlapping with all previously positioned links
        $.each(positions, function(){
            if (dim.left < this.left + this.width &&
                dim.left + dim.width > this.left &&
                dim.top < this.top + this.height &&
                dim.top + dim.height > this.top)
            {
                success = false;
            }
        });
    }
    positions.push(dim);
    ctx.animate({
        left: dim.left,
        top: dim.top
    }, "slow");
});
于 2011-06-10T06:46:31.793 回答
0

您可以将位置值更改为relative

见我的例子:http: //jsfiddle.net/NmmX6/2/

我改变了你的循环,使它不依赖于 id :

function moveAll() {
    $('.navigationItem').each(function(i,e){
        var rdm = Math.random() * 500;
        $(e).animate({"left":rdm + "px"}, "slow");
        $(e).animate({"top": rdm + "px"}, "slow");
    });
}

我对其进行了测试,并没有发现它实际上重叠的一种情况,但请检查一下。

于 2011-06-10T07:43:10.350 回答