使用jQuery .position或.offset检查是否有另一个元素触及/重叠它

时间:2012-01-08 22:07:44

标签: jquery html jquery-ui-draggable

  

可能重复:
  jQuery/Javascript collision detection

最好使用$.position来检查<div>是否被另一个<div>触及或重叠?

谢谢!

1 个答案:

答案 0 :(得分:0)

这是我写的一段时间的功能:

var percentCovered = function (dim1, dim2) {
    // The whole thing is covering the whole other thing
    if (
            (dim1.left <= dim2.left) && 
            (dim1.top <= dim2.top) && 
            ((dim1.left + dim1.width) >= (dim2.left + dim2.width)) && 
            ((dim1.top + dim1.height) > (dim2.top + dim2.height))
    ) {
            return 100;
    }
    // Only parts may be covered, calculate percentage
    else {
            dim1.right      = dim1.left + dim1.width;
            dim1.bottom     = dim1.top + dim1.height;
            dim2.right      = dim2.left + dim2.width;
            dim2.bottom     = dim2.top + dim2.height;

            var l = Math.max(dim1.left, dim2.left);
            var r = Math.min(dim1.right, dim2.right);
            var t = Math.max(dim1.top, dim2.top);
            var b = Math.min(dim1.bottom, dim2.bottom);

            if (b >= t && r >= l) {
            /* $('<div/>').appendTo(document.body).css({
                            background: 'red', 
                            position:   'absolute',
                            left:       l + 'px', 
                            top:        t + 'px', 
                            width:      (r - l) + 'px', 
                            height:     (b - t) + 'px', 
                            zIndex:     100
                    }); */

                    var percent = (((r - l) * (b - t)) / (dim2.width * dim2.height)) * 100;

            //      alert(percent + '% covered')

                    return percent;
            }
    }

    // Nothing covered, return 0
    return 0;
};

它包含两个对象,每个对象包含width,height,left和top属性。像这样:

var el1     = $('#el-1');
var el2     = $('#el-1');
var offset1 = el1.offset();
var offset2 = el2.offset();
var dim1    = {
    width:  el1.outerWidth(), 
    height: el1.outerHeight(), 
    left:   offset1.left, 
    top:    offset1.top
};
var dim2    = {
    width:  el2.outerWidth(), 
    height: el2.outerHeight(), 
    left:   offset2.left, 
    top:    offset2.top
};

alert(percentCovered(dim1, dim2));

我猜你可以把这个偏移的东西移到函数中,如果你不介意每次调用它时计算它。