你能告诉一个元素是否使用JavaScript触及另一个元素吗?

时间:2015-04-28 10:27:42

标签: javascript html draggable

我想使用JavaScript检查一个div元素(可以拖动)是否正在触及另一个div元素。

以下是一些代码:

<div id="draggable" style="position: absolute;  top: 100px; left: 200px; background-color: red;  width: 100px; height: 100px;"></div>
<div style="background-color: green; width: 100px; height: 100px;"></div>

可以这样做吗?

若然,怎么样?

编辑:我不想使用jQuery,只是简单的旧JavaScript!

1 个答案:

答案 0 :(得分:6)

更完整的解决方案

以下是this answer中标题为“jQuery/Javascript collision detection”的重叠检测功能的“普通旧JavaScript”重写。

两者之间唯一真正的区别是替换了使用jQuery来获取元素位置和宽度来计算边界框。

令人惊讶的是,本机JavaScript使用支持良好的(IE4 +)Element.getBoundingClientRect()方法使这项任务更容易,该方法返回创建getPositions函数返回的位置矩阵所需的四个值。

我为这些框添加了一个单击处理程序,作为如何使用该函数将目标(单击,拖动等)元素与一组选定元素进行比较的简单演示。 但是,我承认jQuery使DOM选择和事件绑定比原生JS更容易。

var boxes = document.querySelectorAll('.box');

boxes.forEach(function (el) {
  if (el.addEventListener) {
      el.addEventListener('click', clickHandler);
  } else {
      el.attachEvent('onclick', clickHandler);
  }
})

var detectOverlap = (function () {
    function getPositions(elem) {
        var pos = elem.getBoundingClientRect();
        return [[pos.left, pos.right], [pos.top, pos.bottom]];
    }

    function comparePositions(p1, p2) {
        var r1, r2;
        if (p1[0] < p2[0]) {
          r1 = p1;
          r2 = p2;
        } else {
          r1 = p2;
          r2 = p1;
        }
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function (a, b) {
        var pos1 = getPositions(a),
            pos2 = getPositions(b);
        return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
    };
})();

function clickHandler(e) {
    
    var elem     = e.target,
        elems    = document.querySelectorAll('.box'),
        elemList = Array.prototype.slice.call(elems),
        within   = elemList.indexOf(elem),
        touching = [];
    if (within !== -1) {
        elemList.splice(within, 1);
    }
    for (var i = 0; i < elemList.length; i++) {
        if (detectOverlap(elem, elemList[i])) {
            touching.push(elemList[i].id);
        }
    }
    if (touching.length) {
        console.log(elem.id + ' touches ' + touching.join(' and ') + '.');
        alert(elem.id + ' touches ' + touching.join(' and ') + '.');
    } else {
        console.log(elem.id + ' touches nothing.');
        alert(elem.id + ' touches nothing.');
    }

}
#box1 {
    background-color: LightSeaGreen;
}
#box2 {
    top: 25px;
    left: -25px;
    background-color: SandyBrown;
}
#box3 {
    left: -50px;
    background-color: SkyBlue;
}
#box4 {
    background-color: SlateGray;
}
.box {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 100px;
    color: White;
    font: bold 72px sans-serif;
    line-height: 100px;
    text-align: center;
    cursor: pointer;
}
.box:hover {
    color: Black;
}
<p>Click a box to see which other boxes are detected as touching it.<br />
<em>If no alert dialog box appears, open your console to view messages.</em></p>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>