How to detect if two <div> elements have collided?

The two divs are simple coloured boxes travelling perpendicular to each other, so no complicated shapes or angles.

推荐答案

var overlaps = (function () {
    function getPositions( elem ) {
        var pos, width, height;
        pos = $( elem ).position();
        width = $( elem ).width();
        height = $( elem ).height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

    function comparePositions( p1, p2 ) {
        var r1, r2;
        r1 = p1[0] < p2[0] ? p1 : p2;
        r2 = p1[0] < p2[0] ? p2 : 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 () {
    var area = $( '#area' )[0],
        box = $( '#box0' )[0],
        html;
    
    html = $( area ).children().not( box ).map( function ( i ) {
        return '<p>Red box + Box ' + ( i + 1 ) + ' = ' + overlaps( box, this ) + '</p>';
    }).get().join( '' );

    $( 'body' ).append( html );
});
body {
    padding: 30px;
    color: #444;
    font-family: Arial, sans-serif;
}

h1 {
    font-size: 24px;
    margin-bottom: 20px;
}

#area {
    border: 2px solid gray;
    width: 500px;
    height: 400px;
    position: relative;
}

#area > div {
    background-color: rgba(122, 122, 122, 0.3);
    position: absolute;
    text-align: center;
    font-size: 50px;
    width: 60px;
    height: 60px;
}

#box0 {
    background-color: rgba(255, 0, 0, 0.5) !important;
    top: 150px;
    left: 150px;
}

#box1 {
    top: 260px;
    left: 50px;
}

#box2 {
    top: 110px;
    left: 160px;
}

#box3 {
    top: 200px;
    left: 200px;
}

#box4 {
    top: 50px;
    left: 400px;
}

p {
    margin: 5px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<h1>Detect overlapping with JavaScript</h1>
<div id="area">
    <div id="box0"></div>
    <div id="box1">1</div>
    <div id="box2">2</div>
    <div id="box3">3</div>
    <div id="box4">4</div>
</div>

General idea - you get the offset and dimension of the boxes and check whether they overlap.

If you want it to update, you can use setInterval:

function detectOverlapping() {
    // code that detects if the box overlaps with a moving box
    setInterval(detectOverlapping, 25);
}

detectOverlapping();  

Also, note that you can optimize the function for your specific example.

  • you don't have to read the box dimensions repeatedly (like I do in my code) since they are fixed. You can read them on page load (into a variable) and then just read the variable

  • 小方框的水平位置不变(除非用户调整窗口大小).车厢的垂直位置不变.因此,这些值也不必重复读取,但也可以存储到变量中.

  • 你不必测试这个小盒子是否一直与所有的汽车盒子重叠.您可以-基于其垂直位置-计算出箱子当前位于哪个车道,并仅测试该车道中的特定汽车箱子.

Jquery相关问答推荐

5 秒后关闭 jQuery 弹出模式

Sheets从多张sheet中导入range匹配数据

jQuery 或 JavaScript 中的$符号是什么意思?

缺少 .map 资源?

在范围内设置文本

组合数组时无法读取未定义的属性推送

对混合的字母/数字数组进行排序

jQuery UI 对话框 - 关闭后不打开

如何正确卸载/销毁 VIDEO 元素

jQuery .get 错误响应函数?

禁用表单提交上的提交按钮

jQuery:value.attr 不是函数

在jQuery中添加ID?

为什么不推荐$().ready(handler)?

将图像 url 转换为 Base64

jQuery:如果页面底部有外部 JS,为什么要使用 document.ready?

如何使 jQuery Contains 不区分大小写,包括 jQuery 1.8+?

设置 JQuery event.preventDefault() 时绕过 window.open 上的弹出窗口阻止程序

如何使用 jQuery 的 form.serialize 但排除空字段

Bootstrap:在 Modal 中打开另一个 Modal