87,914
社区成员
发帖
与我相关
我的任务
分享
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>test</title>
<script>
/*
* 获取元素距BODY上边框的距离
*/
function getTop(obj){
var height = 0;
while(obj.tagName.toUpperCase() != "BODY")
{
height+=obj.offsetTop;
obj = obj.offsetParent;
}
return height;
}
/*
* 获取元素距BODY左边框的距离
*/
function getLeft(obj){
var width = 0;
while(obj.tagName.toUpperCase() != "BODY")
{
width+=obj.offsetLeft;
obj = obj.offsetParent;
}
return width;
}
window.onload = function(){
var txt1 = document.getElementById("txt1");
alert(getTop(txt1));
alert(getLeft(txt1));
var txt2 = document.getElementById("txt2");
alert(getTop(txt2));
alert(getLeft(txt2));
};
</script>
</head>
<body>
<div style="position:absolute;left:100px;top:200px">
<input type=text value="" id="txt1"/>
<input type=text value="" id="txt2"/>
</div>
</body>
</html>
var getPosition=function(_obj) {
var x = 0, y = 0;
do{
x += _obj.offsetLeft;
y += _obj.offsetTop;
}while(_obj=_obj.offsetParent);
return {'x':x,'y':y};
};