判断两个矩形是否接触重叠(附js代码)

发布于 2018-12-26  339 次阅读


以下有两个方法判断
第一个。。。暂时没理解
第二个 就是比如以obj1矩形 为固定,obj2矩形为位置不定,
同时满足以下四个条件,就是判断obj2四个边是同时都在obj1边的边界范围内
这个坐标值是以页面中元素相对于屏幕边的距离 也就是 left top bottom right
判断obj2的顶边x坐标值是否大于obj1的底边
判断obj2的底边x坐标值是否小于obj1的定边
判断obj2的左边y坐标值是否小于obj1的右边
判断obj2的右边y坐标值是否大于obj1的左边

//判断是否重叠
//obj1 obj2 为jquery对象
function isOverlap(obj1, obj2) {
var offsetOne = obj1.offset();
var offsetTwo = obj2.offset();
var x1 = offsetOne.left;
var y1 = offsetOne.top;
var x2 = x1 + obj1.width();
var y2 = y1 + obj1.height();

var x3 = offsetTwo.left;
var y3 = offsetTwo.top;
var x4 = x3 + obj2.width();
var y4 = y3 + obj2.height();

var zx = Math.abs(x1 + x2 - (x3 + x4));
var x = obj1.width() + obj2.width()
var zy = Math.abs(y1 + y2 - (y3 + y4));
var y = obj1.height() + obj2.height()
return (zx <= x && zy <= y);
}

//obj1 obj2 为jquery对象
function isOverlap1(obj1, obj2) {
var x1 = obj1.offset().left
var y1 = obj1.offset().top
var x2 = x1 + obj1.width()
var y2 = y1 + obj1.height()
var x3 = obj2.offset().left
var y3 = obj2.offset().top
var x4 = x3 + obj2.width()
var y4 = y3 + obj2.height()
return x3 < x2 && x4 > x1 && y1 < y4 && y2 > y3
}

LoneKing