首页 新闻 会员 周边 捐助

请问怎么用jQuery判断两个元素是否有重叠部分?

1
[已解决问题] 解决于 2012-07-25 11:21

请问怎么用jQuery判断两个元素是否有重叠部分?

草根程序猿的主页 草根程序猿 | 初学一级 | 园豆:129
提问于:2012-07-25 10:42
< >
分享
最佳答案
0
<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(isOverlap("one","two"));//true
    console.log(isOverlap("one","three"));//false
    console.log(isOverlap("two","three"));//true
    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;
    }
</script>

Demo:http://jscode.chinacxy.com/code/e72050b3f22a658fa69470a39788ab00.aspx

奖励园豆:5
artwl | 专家六级 |园豆:16736 | 2012-07-25 11:13
其他回答(1)
0

你可以看看 jq ui 里面的 droppable

http://jqueryui.com/demos/droppable/#visual-feedback

要么就自己写代码判断,根据元素位置!

张坤 | 园豆:1865 (小虾三级) | 2012-07-25 10:49
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册