js位置定位

 offsetParent从字面上理解,这是在查找元素的父亲.可实际应用中,根据浏览器他会返回不同的结果.在Opera较低版本中返回被引用元素的直接父元素,在IE中使用offsetParent有时会返回body元素,有时会返回被引用元素的父元素.为什么IE会这样.我会在下面的实例演示中解释清楚.而在FireFox中他总是返回body元素.  

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body style=" margin:0px; padding:0px;">
<div style="height:300px; width::100%;"></div>

<div>
<div style="height:300px; width::300px; float:left; background-color:gray;">
<input type="button" name="Submit" value="点击获取元素坐标" style=" margin:0px; padding:0px;" onclick="getPosition(this)"/>
<input name="textfield" type="text" value="点击获取元素坐标" style=" margin:0px; padding:0px;" onclick="getPosition(this)"/>
</div>
<div style=" float:left;width::200px; background-color:red; height:500px;">
asdfasdf
</div>
</div>

 

<script>
function getPosition(o)
{
var left=o.offsetLeft;
var top=o.offsetTop;
var p=o.offsetParent;
  while(p!== null){
left+=p.offsetLeft;
top+=p.offsetTop;
p=p.offsetParent;
  }
var width=o.offsetWidth;
var height=o.offsetHeight;
alert("top=" + top + ",left=" + left + ",width=" + width + ",height=" + height);

}
</script>
</body>
</html>

posted @ 2012-07-10 23:03  枫-  阅读(505)  评论(0编辑  收藏  举报