用jQuery判断两个元素是否有重叠部分

  这是博问中的一个问题:http://q.cnblogs.com/q/39172/

  我的方案如下:

function isOverlap(idOne,idTwo){
    var objOne=$("#"+idOne),
        objTwo=$("#"+idTwo),
        offsetOne = objOne.offset(),
        offsetTwo = objTwo.offset(),
        topOne=offsetOne.top,
        topTwo=offsetTwo.top,
        leftOne=offsetOne.left,
        leftTwo=offsetTwo.left,
        widthOne = objOne.width(),
        widthTwo = objTwo.width(),
        heightOne = objOne.height(),
        heightTwo = objTwo.height();
    var leftTop = leftTwo > leftOne && leftTwo < leftOne+widthOne 
            && topTwo > topOne && topTwo < topOne+heightOne,
        rightTop = leftTwo+widthTwo > leftOne && leftTwo+widthTwo < leftOne+widthOne 
            && topTwo > topOne && topTwo < topOne+heightOne,
        leftBottom = leftTwo > leftOne && leftTwo < leftOne+widthOne 
            && topTwo+heightTwo > topOne && topTwo+heightTwo < topOne+heightOne,
        rightBottom = leftTwo+widthTwo > leftOne && leftTwo+widthTwo < leftOne+widthOne 
            && topTwo+heightTwo > topOne && topTwo+heightTwo < topOne+heightOne;
    return leftTop || rightTop || leftBottom || rightBottom;
}

  原理很简单,就是判断一个元素的四个点是否在另一个元素内部。

  Demo:

  如果有其他方案欢迎提出。

posted @ 2012-07-25 11:20  artwl  阅读(1296)  评论(0编辑  收藏  举报

个人简介

var ME = {
	"name": "土豆/Artwl",
	"job": "coding",
	"languages": [
		"JS", "HTML",
                "CSS", "jQuery"
		"MVC",".NET",
		"设计模式"
	],
	"hobby": [
		"阅读", "旅游",
		"音乐", "电影"
	]
}
TOP