【问题标题】:Use jQuery .position or .offset to check if there is another element touching/overlapping it [duplicate]使用 jQuery .position 或 .offset 检查是否有另一个元素接触/重叠它[重复]
【发布时间】:2012-01-09 06:40:37
【问题描述】:

可能重复:
jQuery/Javascript collision detection

最好使用$.position 来检查<div> 是否被另一个<div> 触摸或重叠,最好的方法是什么?

谢谢!

【问题讨论】:

标签: jquery html jquery-ui-draggable


【解决方案1】:

这是我不久前写的一个函数:

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

它将两个对象作为参数,每个对象包含宽度、高度、左侧和顶部属性。像这样:

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

如果您不介意每次调用它时都计算它,我想您可以将偏移量移到函数中。

【讨论】:

  • 是的,谢谢,我最终使用顶部、左侧、宽度和高度编写了类似的内容。它没有那么复杂,因为 div 没有任何疯狂的角度或形状!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 2015-03-01
  • 2012-08-17
  • 2015-12-19
相关资源
最近更新 更多