示例代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>365codes.com</title>
</head>
<body>
	<input id="usernameId"></input>
</body>
    <script type="text/javascript">
	function getLeft(e){
	  var offset=e.offsetLeft;
	  if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);
	  return offset;
	}
	 
	function getTop(e){
	  var offset=e.offsetTop;
	  if(e.offsetParent!=null) offset+=getTop(e.offsetParent);
	  return offset;
	}
	 
	var element = document.getElementById('usernameId');
	alert("对象usernameId的坐标x="+getTop(element)+",y="+getLeft(element)+";宽度w="+element.offsetWidth+",高度h="+element.offsetHeight);
	</script>
</html>

JS获取位置和尺寸:

obj.clientWidth //获取元素的宽度(width+padding)
obj.clientHeight //元素的高度
obj.offsetLeft //元素相对于父元素的left
obj.offsetTop //元素相对于父元素的top
obj.offsetWidth //元素的宽度(width+padding+border)
obj.offsetHeight //元素的高度

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐