首页 > web前端 > js教程 > 基于jQuery判断两个元素是否有重叠部分的代码_jquery

基于jQuery判断两个元素是否有重叠部分的代码_jquery

WBOY
发布: 2016-05-16 17:51:41
原创
1265 人浏览过

核心代码:

复制代码 代码如下:

$("#result").text(isOverlap("one","two")+","+isOverlap("one","three")+","+isOverlap("two","three"));
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 && topTwo > topOne && topTwo rightTop = leftTwo+widthTwo > leftOne && leftTwo+widthTwo && topTwo > topOne && topTwo leftBottom = leftTwo > leftOne && leftTwo && topTwo+heightTwo > topOne && topTwo+heightTwo rightBottom = leftTwo+widthTwo > leftOne && leftTwo+widthTwo && topTwo+heightTwo > topOne && topTwo+heightTwo return leftTop || rightTop || leftBottom || rightBottom;
}

原理很简单,就是判断一个元素的四个点是否在另一个元素内部。
完整演示代码:
复制代码 代码如下:

JSCode
LoginResult JavaScript HTML CSS ALL Edit Share
$("#result").text(isOverlap("one","two")+","+isOverlap("one","three")+","+isOverlap("two","three"));
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 && topTwo > topOne && topTwo rightTop = leftTwo+widthTwo > leftOne && leftTwo+widthTwo && topTwo > topOne && topTwo leftBottom = leftTwo > leftOne && leftTwo && topTwo+heightTwo > topOne && topTwo+heightTwo rightBottom = leftTwo+widthTwo > leftOne && leftTwo+widthTwo && topTwo+heightTwo > topOne && topTwo+heightTwo return leftTop || rightTop || leftBottom || rightBottom;
}
One

Two

Three


div{
width:200px;
height:200px;
background:#EEE;
}
#two{
position:absolute;
left:100px;
top:50px;
background:#F60;
}
DownLoad




JSCode demo




One

Two

Three





Share link
Embed on your page
Share on Sina
Share on QQ

作者:Artwl
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板