你如何检测使用 JQuery 碰撞的多个 div 元素?我找到了一个解决方案,但它只检测到两个元素。您如何将多个 div ID 传递给该函数?
HTML:
<strong>Drag divs around.</strong>
<div id="div1">
Div1
</div><br/>
<div id="div2">
Div2
</div>
<p>Colliding? <span id="result">false</span>
CSS:
#div1 { width: 200px; height: 50px; background-color: pink; }
#div2 { width: 400px; height: 100px; background-color: green; }
jQuery:
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var y1 = $div1.offset().top;
var h1 = $div1.outerHeight(true);
var w1 = $div1.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var y2 = $div2.offset().top;
var h2 = $div2.outerHeight(true);
var w2 = $div2.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
return true;
}
window.setInterval(function() {
$('#result').text(collision($('#div1'), $('#div2')));
}, 200);
$('#div1,#div2').draggable();