您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

jQuery / JavaScript冲突检测

jQuery / JavaScript冲突检测

var overlaps = (function () {

    function getPositions( elem ) {

        var pos, width, height;

        pos = $( elem ).position();

        width = $( elem ).width();

        height = $( elem ).height();

        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];

    }



    function comparePositions( p1, p2 ) {

        var r1, r2;

        r1 = p1[0] < p2[0] ? p1 : p2;

        r2 = p1[0] < p2[0] ? p2 : p1;

        return r1[1] > r2[0] || r1[0] === r2[0];

    }



    return function ( a, b ) {

        var pos1 = getPositions( a ),

            pos2 = getPositions( b );

        return comparePositions( pos1[0], pos2[0] ) && comparePositions( pos1[1], pos2[1] );

    };

})();



$(function () {

    var area = $( '#area' )[0],

        @R_367_2419@ = $( '#@R_367_2419@0' )[0],

        html;



    html = $( area ).children().not( @R_367_2419@ ).map( function ( i ) {

        return '<p>Red @R_367_2419@ + @R_367_2419@ ' + ( i + 1 ) + ' = ' + overlaps( @R_367_2419@, this ) + '</p>';

    }).get().join( '' );



    $( 'body' ).append( html );

});


body {

    padding: 30px;

    color: #444;

    font-family: Arial, sans-serif;

}



h1 {

    font-size: 24px;

    margin-bottom: 20px;

}



#area {

    border: 2px solid gray;

    width: 500px;

    height: 400px;

    position: relative;

}



#area > div {

    background-color: rgba(122, 122, 122, 0.3);

    position: absolute;

    text-align: center;

    font-size: 50px;

    width: 60px;

    height: 60px;

}



#@R_367_2419@0 {

    background-color: rgba(255, 0, 0, 0.5) !important;

    top: 150px;

    left: 150px;

}



#@R_367_2419@1 {

    top: 260px;

    left: 50px;

}



#@R_367_2419@2 {

    top: 110px;

    left: 160px;

}



#@R_367_2419@3 {

    top: 200px;

    left: 200px;

}



#@R_367_2419@4 {

    top: 50px;

    left: 400px;

}



p {

    margin: 5px 0;

}


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<h1>Detect overlapping with JavaScript</h1>

<div id="area">

    <div id="@R_367_2419@0"></div>

    <div id="@R_367_2419@1">1</div>

    <div id="@R_367_2419@2">2</div>

    <div id="@R_367_2419@3">3</div>

    <div id="@R_367_2419@4">4</div>

</div>

一般思路-获得框的偏移量和尺寸,并检查它们是否重叠。

如果要更新,可以使用setInterval

function detectOverlapping() {
    // code that detects if the @R_367_2419@ overlaps with a moving @R_367_2419@
    setInterval(detectOverlapping, 25);
}

detectOverlapping();

另外,请注意,您可以针对特定示例优化功能

因为它们是固定的,所以您不必重复读取框的尺寸(就像我在代码中一样)。您可以在页面加载时读取它们(将其读取到变量中),然后仅读取变量

小盒子的水平位置不会改变(除非用户调整窗口大小)。轿厢的垂直位置不变。因此,这些值也不必重复读取,也可以存储到变量中。

您无需测试小盒子是否始终与所有汽车盒子重叠。您可以-基于其垂直位置-确定当前箱子在哪个车道上,并仅从该车道测试特定的汽车箱子。

javascript 2022/1/1 18:15:21 有490人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶