Javascript:检测碰撞的 div
如何检测两个 div 是否重叠?
不考虑 div 的宽度,它基本上是一个垂直线段。 (顶部,左侧)点是 A 点,而底部(顶部 + 高度)是 B 点,依此类推。然后,我将每个 div 与 div 数组中的其他 div 进行比较,然后创建一个冲突 div 数组。但是,我一直不知道如何以编程方式执行此操作。
这是我的 div 数组:
var divs = [
{class:'A', top:0, left:0, height:'60px'},
{class:'B', top:50, left:60, height:'60px'},
{class:'C', top:30, left:10, height:'60px'},
{class:'D', top:100, left:180, height:'60px'},
{class:'E', top:80, left:50, height:'60px'},
{class:'F', top:110, left:200, height:'60px'},
{class:'G', top:55, left:80, height:'60px'}
];
这是我启动的函数:
this.collide = function( divs )
{
var collidingDivs = [], z = events.length;
for(i; i<z; i++)
{
if
(
// Begin pseudocode
( divsB.top >= divsA.top ) &&
( (divsB.top + divsB.height) <= (divsA.top + divsA.height) )
)
{
collidingDivs.push(divs[i].class);
}
}
console.log(collidingDivs); // Array of divs that overlap (collide)
};
我完全陷入了这一点。如何迭代每个 div 并检查它是否与任何其他 div 发生冲突?
How do I detect if two divs are overlapping?
Not taking into consideration the width of a div, it is basically a vertical line segment. The (top,left) point is point A while the bottom (top + height) is point B and so forth. I'd then compare each div to each to the other divs in the divs array and then create an array of colliding divs. However, I'm stuck on how to do this programmatically.
This is my array of divs:
var divs = [
{class:'A', top:0, left:0, height:'60px'},
{class:'B', top:50, left:60, height:'60px'},
{class:'C', top:30, left:10, height:'60px'},
{class:'D', top:100, left:180, height:'60px'},
{class:'E', top:80, left:50, height:'60px'},
{class:'F', top:110, left:200, height:'60px'},
{class:'G', top:55, left:80, height:'60px'}
];
Here's the function I had started:
this.collide = function( divs )
{
var collidingDivs = [], z = events.length;
for(i; i<z; i++)
{
if
(
// Begin pseudocode
( divsB.top >= divsA.top ) &&
( (divsB.top + divsB.height) <= (divsA.top + divsA.height) )
)
{
collidingDivs.push(divs[i].class);
}
}
console.log(collidingDivs); // Array of divs that overlap (collide)
};
I'm just utterly stuck at this point. How do I iterate over each div and check if it collides with any of the other divs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要循环遍历每个 div,然后与嵌套循环中的每个其他 div 进行比较。然后使用您所编写的逻辑来比较每个组合。下面是一个简单地将重叠的 div 打印到输出的示例(另请注意,我将
height
元素更改为具有数值而不是文本,以便其值可以用于计算): :
示例工作代码: http://jsfiddle.net/QUrWM/
You need to loop through each div, and then compare with every other div in a nested loop. Then use logic like what you've written to compare each combination. Here is an example that simply prints out the overlapping divs to the output (note also that I changed the
height
element to have a numerical value rather than text so that its value could be used in calculations):Output:
Sample working code: http://jsfiddle.net/QUrWM/