判断可拖动div是否重合,需要考虑以下几个步骤:
判断两个div是否重合,首要条件是要获取它们的位置以及大小。可以通过jQuery中的offset和width/height方法获取其在页面上的位置和大小。例如:
var $div1 = $("#div1");
var $div2 = $("#div2");
var div1X = $div1.offset().left;
var div1Y = $div1.offset().top;
var div1Width = $div1.outerWidth(true);
var div1Height = $div1.outerHeight(true);
var div2X = $div2.offset().left;
var div2Y = $div2.offset().top;
var div2Width = $div2.outerWidth(true);
var div2Height = $div2.outerHeight(true);
在得到div的位置和大小之后,接下来就是需要判断这两个div是否重叠了。判断方法是比较两个div的位置和大小,如果存在重叠区域,即两个div的水平和垂直距离均小于它们的宽度和高度之和,那么它们就是重叠的。可以通过以下代码进行判断:
var overlapX = Math.max(0, Math.min(div1X + div1Width, div2X + div2Width) - Math.max(div1X, div2X));
var overlapY = Math.max(0, Math.min(div1Y + div1Height, div2Y + div2Height) - Math.max(div1Y, div2Y));
if (overlapX > 0 && overlapY > 0) {
// 两个div重叠了
}
其中overlapX和overlapY分别代表两个div在水平和垂直方向上的重叠长度。
如果判断出两个div重叠了,接下来可以计算重叠面积。可以通过overlapX和overlapY计算重叠面积,即两个div的重叠面积为:overlapX * overlapY。
示例一:
HTML代码:
<div id="div1" class="draggable"></div>
<div id="div2" class="draggable"></div>
JS代码:
$(function() {
$(".draggable").draggable();
$("#div2").css("left", "200px");
$("#div2").css("top", "200px");
var $div1 = $("#div1");
var $div2 = $("#div2");
var div1X = $div1.offset().left;
var div1Y = $div1.offset().top;
var div1Width = $div1.outerWidth(true);
var div1Height = $div1.outerHeight(true);
var div2X = $div2.offset().left;
var div2Y = $div2.offset().top;
var div2Width = $div2.outerWidth(true);
var div2Height = $div2.outerHeight(true);
var overlapX = Math.max(0, Math.min(div1X + div1Width, div2X + div2Width) - Math.max(div1X, div2X));
var overlapY = Math.max(0, Math.min(div1Y + div1Height, div2Y + div2Height) - Math.max(div1Y, div2Y));
if (overlapX > 0 && overlapY > 0) {
var overlapArea = overlapX * overlapY;
alert("两个div重叠了,重叠面积为:" + overlapArea);
} else {
alert("两个div没有重叠");
}
});
在该示例中,div1和div2都是可拖动的,通过拖动它们可以实现二维平面的移动。在代码中,我们将div2向右下角移动了200px,使其与div1有重叠。运行代码后,会弹出一个提示框,提示“两个div重叠了,重叠面积为:20000”。
示例二:
HTML代码:
<div id="div1" class="draggable"></div>
<div id="div2" class="draggable"></div>
JS代码:
$(function() {
$(".draggable").draggable();
var $div1 = $("#div1");
var $div2 = $("#div2");
var div1X = $div1.offset().left;
var div1Y = $div1.offset().top;
var div1Width = $div1.outerWidth(true);
var div1Height = $div1.outerHeight(true);
var div2X = $div2.offset().left;
var div2Y = $div2.offset().top;
var div2Width = $div2.outerWidth(true);
var div2Height = $div2.outerHeight(true);
var overlapX = Math.max(0, Math.min(div1X + div1Width, div2X + div2Width) - Math.max(div1X, div2X));
var overlapY = Math.max(0, Math.min(div1Y + div1Height, div2Y + div2Height) - Math.max(div1Y, div2Y));
if (overlapX > 0 && overlapY > 0) {
var overlapArea = overlapX * overlapY;
alert("两个div重叠了,重叠面积为:" + overlapArea);
} else {
alert("两个div没有重叠");
}
});
在该示例中,div1和div2的位置是不同的,因此它们不会重叠。运行代码后,会弹出一个提示框,提示“两个div没有重叠”。
本文链接:http://task.lmcjl.com/news/8210.html