Home  >  Article  >  Web Front-end  >  Code to determine whether two elements overlap based on jQuery_jquery

Code to determine whether two elements overlap based on jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 17:51:411204browse

核心代码:

复制代码 代码如下:

$("#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 < 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;
}

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

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 < 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;
}
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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn