判断鼠标坐标是否属于div内

Posted on 2010-05-18 15:01  pumeifen  阅读(620)  评论(0编辑  收藏  举报

 

<div id="test" style="position:absolute; width:200px; height:200px; border:1px solid #ccc; top:100px; left:100px; background:red;"></div>
02 <script type="text/javascript">
03 function getELXY(e){
04    return {x:e.offsetLeft,y:e.offsetTop};
05 }
06 function getELWH(e){
07    return {w:e.offsetWidth,h:e.offsetHeight};
08 }
09 function getClientXY(e){
10    e=e||event;
11    return {cx:e.clientX,cy:e.clientY};
12 }
13 document.onclick = function(e){
14    var obj = document.getElementById("test");
15    var lt = getELXY(obj)['x'];
16    var rt = getELXY(obj)['x'] + getELWH(obj)['w'];
17    var topY = getELXY(obj)['y'];
18    var bottomY = getELXY(obj)['y'] + getELWH(obj)['h'];
19    var mouseXX = getClientXY(e)['cx'];
20    var mouseYY = getClientXY(e)['cy'];
21    if(mouseXX&lt;lt || mouseXX>rt || mouseYY<topY || mouseYY>bottomY){
22       obj.style.display="none";
23    }else{
24    }
25 };
26 </script>