2012-10-17 来源:网络
【实例名称】
如何利用JS代码取得控件的绝对位置
【实例描述】
页面在布局时一般需要相对位置和绝对位置,本例学习如何获取控件的绝对位置。
【实例代码】
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>标题页</title>
<script language="javascript">
function getAddress(e)
{
var t=e.offsetTop;
var l=e.offsetLeft;
while(e=e.offsetParent)
{
t+=e.offsetTop; //获取X坐标
l+=e.offsetLeft; //获取Y坐标
}
alert("x坐标="+t+" y坐标为="+l);
}
</script>
</head>
<body>
<input id="Button1" type="button" value="坐标" onclick="getAddress(this)" />
</body>
</html>
【运行效果】

【难点剖析】
本例的重点有两个:如何将当前元素作为参数传递;如何获取绝对的。(x,y)坐标。传递当前控件使用“this”,获取绝对x坐标使用“offsetTop”属性,Y坐标使用“offsetLeft”属性。
【源码下载】