jQuery-如何使用jQuery来判断页面上2个div块是否有交集?

小组事务管理 小组事务管理 主题:974 回复:1955

jQuery-如何使用jQuery来判断页面上2个div块是否有交集?

偏爱自由 发布于 2017-04-16 字数 126 浏览 953 回复 1

希望有个独立的方法,jquery实现,判断2个块是否有交集。

function isOverlapped(div1, div2){
//实现代码
}

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

支持 Markdown 语法,需要帮助?

评论(1

夜无邪 2017-09-23 1 楼

做了一个简单的例子,你可以看下(参数可能需要改造下哦):

<style type="text/css">
div{
width:200px;
height:200px;
background:#EEE;
}

two{

    position:absolute;
    left:100px;
    top:50px;
    background:#F60;
}

</style>
<div id="one">One</div>
<div id="two">Two</div>
<div id="three">Three</div>
<script>
console.log(isOverlapped("one","two"));//true
console.log(isOverlapped("one","three"));//false
console.log(isOverlapped("two","three"));//true
function isOverlapped(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;
}
</script>