jsコントロール座標を取得する

2338 ワード

<HTML>   
 <BODY>   
 <div id="mydiv" style="position:absolute; display:none; background:#FF9933; height:80;width:120;"> I am div ^_^ <button onclick="sss()">showDiv</button>   </div>   
   showDiv            DIV<br>   
 <table border=1>   
    <tr>   
        <td>   
            <table border=1>   
                <tr>   
                    <td>aa</td>   
                    <td>   
                        <input type="text" id="test">   
                        <button onclick="showDiv()">showDiv</button>   
                    </td>   
                </tr>   
            </table>   
        </td>   
    </tr>   
  </table>   
  
  <SCRIPT LANGUAGE="JavaScript">   
  <!--   
//           ,                  
function getElementPos(obj)   
{   
    var left = 0;   
    var top = 0;   
  
    if(obj.x)   
    {   
        left= obj.x;   
        top = obj.y;   
    }else if(obj.offsetParent)   
    {      
        while(obj.offsetParent)   
        {          
            left += obj.offsetLeft;   
            top  += obj.offsetTop;   
            obj = obj.offsetParent;   
        }    
    }   
  
    return [left,top];//           
}   
function showDiv()   
{   
    var mydiv = document.getElementById("mydiv");   
    var pos = getElementPos(document.getElementById("test"));   
    mydiv.style.display = "";   
  
    mydiv.style.left = pos[0];   
    mydiv.style.top = pos[1] + document.getElementById("test").offsetHeight;   
}   
function sss()   
{   
    var mydiv = document.getElementById("mydiv");   
    var pos = getElementPos(document.getElementById("test"));   
    mydiv.style.display = "none";   
}  
  //-->   
  </SCRIPT>   
 </BODY>   
</HTML>