添加元素不重叠

时间:2015-09-28 03:27:31

标签: javascript jquery overlap

我已经阅读过关于如何随机定位元素的问题,并且它完美无缺。 Positioning multiple, random sized, absolutely positioned elements so they don't overlap

当他们随意定位时,如何让圆圈不与中心的徽标重叠?

JSFiddle:http://jsfiddle.net/2h8783ba/

var maxSearchIterations = 10;
var min_x = 110;
var max_x = window.innerWidth - 310;
var min_y = 110;
var max_y = window.innerHeight - 310;
var filled_areas = [];

function calc_overlap(a1) {
var overlap = 0;
for (i = 0; i < filled_areas.length; i++) {

    var a2 = filled_areas[i];

    // no intersection cases
    if (a1.x + a1.width < a2.x) {
        continue;
    }
    if (a2.x + a2.width < a1.x) {
        continue;
    }
    if (a1.y + a1.height < a2.y) {
        continue;
    }
    if (a2.y + a2.height < a1.y) {
        continue;
    }

    // intersection exists : calculate it !
    var x1 = Math.max(a1.x, a2.x);
    var y1 = Math.max(a1.y, a2.y);
    var x2 = Math.min(a1.x + a1.width, a2.x + a2.width);
    var y2 = Math.min(a1.y + a1.height, a2.y + a2.height);

    var intersection = ((x1 - x2) * (y1 - y2));

    overlap += intersection;
}
return overlap;
}

function randomize() {

filled_areas.splice(0, filled_areas.length);

var index = 0;
$('.c1, .c2, .c3, .c4').each(function() {
    var rand_x = 0;
    var rand_y = 0;
    var i = 0;
    var smallest_overlap = 9007199254740992;
    var best_choice;
    var area;
    for (i = 0; i < maxSearchIterations; i++) {
        rand_x = Math.round(min_x + ((max_x - min_x) * (Math.random() % 1)));
        rand_y = Math.round(min_y + ((max_y - min_y) * (Math.random() % 1)));
        area = {
            x: rand_x,
            y: rand_y,
            width: $(this).width(),
            height: $(this).height()
        };
        var overlap = calc_overlap(area);
        if (overlap < smallest_overlap) {
            smallest_overlap = overlap;
            best_choice = area;
        }
        if (overlap === 0) {
            break;
        }
    }

    filled_areas.push(best_choice);

    $(this).css({
        position: "absolute",
        "z-index": index++
    });
    $(this).animate({
        left: rand_x,
        top: rand_y
    });
});
return false;
}

1 个答案:

答案 0 :(得分:1)

这是解决方案。

Css

#logo-content{
position: absolute;
left: 50%;
margin-left: -100px;
top: 50%;
margin-top: -100px;
z-index: 10;
}

HTML

  <div id="wrapper">
   <div id="logo-content">
    <svg version="1.1" id="logo" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 93.7 93.7"      enable-background="new 0 0 93.7 93.7" xml:space="preserve"></svg>
   <div>
 </div>