如何检测两个div是否碰到jquery? [英] How to detect if two divs touch with jquery?
本文介绍了如何检测两个div是否碰到jquery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
函数碰撞($ 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 b2 || r1 r2)return false;
返回true;
}
I'm just developing a simple balloon game with two divs. The problem is that I'm unable to trigger a function when the two divs touch each other.
解决方案
You're looking for bounding box collision detection. If you want to raise an event, you have to repeatedly test, but it would be better just to run the function over all your game objects from your game loop. The sandbox is at http://jsfiddle.net/nGRwt/7/
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;
}
这篇关于如何检测两个div是否碰到jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文