Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

html - Can you tell if one element is touching another using JavaScript?

I want to use JavaScript to check if one div element (that can be dragged) is touching another div element.

Here is some code:

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

Can this be done?

If so, how?

Edit: I do not want to use jQuery, just plain old JavaScript!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A more complete solution

Below is a "plain old JavaScript" rewrite of the overlap detection function found in this answer to the question titled "jQuery/Javascript collision detection".

The only real difference between the two is the replacement of the use of jQuery to get element position and width for calculating the bounding box.

Surprisingly, native JavaScript makes this task easier with the well-supported (IE4+) Element.getBoundingClientRect() method, which returns the four values needed to create the position matrix returned by the getPositions function.

I added a click handler for the boxes as a simple demonstration of how you might use the function to compare a target (clicked, dragged, etc.) element to a set of selected elements. I will concede, however, that jQuery makes DOM selection and event binding much easier than native 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...