发新话题
打印

如何得到某元素的坐標

如何得到某元素的坐標

比如一個單元格,一個按鈕,一張圖片,一段文字等等  
假設我已為上述元素定義了ID  
比如  
<td  id="t1"></td>  
<img  id="i1"  src="...">  
<input  type="text"  id="x1">  
<span  id="s1">test...</span>  
....  
如何得到他們的坐標呢(我指的是左上角的X與Y值就行了)  
先謝謝了~~~

TOP

<script  language="Javascript">  
function  getIE(e)  
{  
     var  t=e.offsetTop;  
     var  l=e.offsetLeft;  
     while(e=e.offsetParent)  
     {  
           t+=e.offsetTop;  
           l+=e.offsetLeft;  
     }  
     alert("top="+t+"\nleft="+l);  
}  
</script>  

<body><input  type=button  onclick="getIE(this)">

TOP

<html>  
<head>  
   <title>IE与NS都支持的实时读取鼠标位置的例子</title>  
   <meta  http-equiv="Content-Type"  content="text/html;  charset=gb2312">  
   <meta  content="F.R.Huang(meizz梅花雨)//www.meizz.com"  name="author">  
</head>  
<body  bgcolor="#fef4d9"  onmousemove="microsoftMouseMove()">  
<form  name="form1">  
X:  <input  type="text"  name="x"  size="4"><br>  
Y:  <input  type="text"  name="y"  size="4">  
</form>  

<SCRIPT  LANGUAGE="JavaScript">  
if  (navigator.appname  ==  'Netscape')  
{  
     document.captureEvents(Event.MOUSEMOVE);  
     document.onmousemove  =  netscapeMouseMove;  
}  
function  netscapeMouseMove(e)  
{  
     if  (e.screenX  !=  document.form1.x.value  &&  e.screenY  !=  document.form1.y.value)  
     {  
           document.form1.x.value  =  e.screenX;  
           document.form1.y.value  =  e.screenY;  
     }  
}  
function  microsoftMouseMove()  
{  
     if  (window.event.x  !=  document.form1.x.value  &&  window.event.y  !=  document.form1.y.value)  
     {  
           document.form1.x.value  =  window.event.x;  
           document.form1.y.value  =  window.event.y;  
     }  
}  
</SCRIPT>  
</body></html>

TOP

发新话题