//获取元素在包含元素框中的大小
//第1个函数为获取元素在包含元素中左内边框的距离
function getELementLeft(element){//获取元素在包含元素左边距离var actualeft=element.offsetLeft;//获取元素的上级包含元素var current=element.offsetParent;//循环到一直没有包含元素while(current !==null){actualeft+=current.offsetLeft;current=current.offsetParent;}return actualeft;}
//第2个函数为获取元素在包含元素中顶部内边框的距离function getElementTop(element){var actuatop=element.offsetTop;var current=element.offsetParent;while(current !==null){actuatop += current.offsetTop;current=current.offsetParent;}return actuatop;}//获取元素在浏览器工作区域中的位置,相对于浏览器工作区域的左、右、上、下的值
function getBoundingClientRect(element){//获取带有垂直滚动条的页面区,包括在上面的隐藏内容的像素数,document.body.scrollTop为兼容IEvar scrollTop=document.documentElement.scrollTop || document.body.scrollTop;//获取带有水平滚动条的页面区,包括在左边的隐藏内容的像素数,document.body.scrollLeft为兼容IEvar scrollLeft=document.documentElement.scrollLeft || document.body.scrollLeft;//检查元素的getBoundingClientRect方法,这个方法是元素自有的,不是我们上面的那个函数名if(element.getBoundingClientRect){//设置arguments.callee的offset属性,才设置肯定为NaN,不等于numberif(typeof arguments.callee.offset !="number"){//创建一个零时的div元素,设置他的left top 为0var temp=document.createElement("div");temp.style.cssText="position:absolute;left:0;top:0;";document.body.appendChild(temp);//让offset获取到值,如果是IE8浏览器以前的为-2arguments.callee.offset=-temp.getBoundingClientRect().top-scrollTop;document.body.removeChild(temp);temp=null;}var rect=element.getBoundingClientRect();//获取offset值var offset=arguments.callee.offset;//返回元素对于浏览器工作区左中上下距离return {left:rect.left + offset,right:rect.right+offset,top:rect.top+offset,bottom:rect.bottom+offset};//如果元素没有element.getBoundingClientRect,则以我们上面两个函数来计算带滚动条的工作区坐标位置}else{var actualLeft=getElementLeft(element);var actualTop=getElementTop(element);}return {left:actualLeft-scrollLeft,right:actualLeft+element.offsetWidth - scrollLeft,top:actulTop-scrollTop,bottom:actualTop+element.offsetHeight - scrollTop} }
var div=document.getElementById("container");
var bd=document.getElementsByClassName("bd")[0];
var size=getBoundingClientRect(bd);
console.log(size.left);
//html代码部分
<div id="container"><div class="bd"></div></div>
//css
<style type="text/css">#container{width: 800px;height: 500px;border: 1px solid #ccc;margin: 0 atuo;margin-top: 50px;}div#container .bd{width:400px;height: 400px;border: solid 1px blue;position: relative;top: 50px;left:100px;}</style>