Overlapping elements - HTML, CSS, and jQuery

此生再无相见时 提交于 2019-11-28 12:51:29

Removing position:absolute would render them side by side.

JSFiddle

But if the whole point is to scatter them around randomly, then you will have to keep track of positioned elements and take that into account when calculating their position. You should save each link's position and calculate every next link's position according to previous already positioned links. There's simply no other way when you want random positions and non overlapping.

Final non-overlapping solution

This is a working example of non-overlapping functionality. If you'd want your links to not even touch, you should change < to <= and > to >= in the if statement condition.

Relevant code

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");
});

You can change the position value to relative.

See my example : http://jsfiddle.net/NmmX6/2/

I changed your loop so that it isn't id dependent :

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

I tested it and did not find one case where it actually overlaps, but check it out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!