Overlapping elements - HTML, CSS, and jQuery

前端 未结 2 914
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 11:48

I have elements which are overlapping and I would like to prevent this. Here is a picture: http://grab.by/cB7t

Also, here is the CSS for those elements:



        
相关标签:
2条回答
  • 2020-12-11 12:21

    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.

    0 讨论(0)
  • 2020-12-11 12:36

    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");
    });
    
    0 讨论(0)
提交回复
热议问题