码迷,mamicode.com
首页 > Web开发 > 详细

js获取页面元素位置函数(跨浏览器)

时间:2014-07-30 11:36:53      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:style   使用   os   io   for   cti   html   ar   

function getElementPos(elementId) {
 var ua = navigator.userAgent.toLowerCase();
 var isOpera = (ua.indexOf(‘opera‘) != -1);
 var isIE = (ua.indexOf(‘msie‘) != -1 && !isOpera); // not opera spoof
 var el = document.getElementById(elementId);
 if(el.parentNode === null || el.style.display == ‘none‘) {
  return false;
 }      
 var parent = null;
 var pos = [];     
 var box;     
 if(el.getBoundingClientRect)    //IE
 {         
  box = el.getBoundingClientRect();
  var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
  return {x:box.left + scrollLeft, y:box.top + scrollTop};
 }else if(document.getBoxObjectFor)    // gecko    
 {
  box = document.getBoxObjectFor(el); 
  var borderLeft = (el.style.borderLeftWidth)?parseInt(el.style.borderLeftWidth):0; 
  var borderTop = (el.style.borderTopWidth)?parseInt(el.style.borderTopWidth):0; 
  pos = [box.x - borderLeft, box.y - borderTop];
 } else    // safari & opera    
 {
  pos = [el.offsetLeft, el.offsetTop];  
  parent = el.offsetParent;     
  if (parent != el) { 
   while (parent) {  
    pos[0] += parent.offsetLeft; 
    pos[1] += parent.offsetTop; 
    parent = parent.offsetParent;
   }  
  }   
  if (ua.indexOf(‘opera‘) != -1 || ( ua.indexOf(‘safari‘) != -1 && el.style.position == ‘absolute‘ )) { 
   pos[0] -= document.body.offsetLeft;
   pos[1] -= document.body.offsetTop;         
  }    
 }              
 if (el.parentNode) { 
    parent = el.parentNode;
   } else {
    parent = null;
   }
 while (parent && parent.tagName != ‘BODY‘ && parent.tagName != ‘HTML‘) { // account for any scrolled ancestors
  pos[0] -= parent.scrollLeft;
  pos[1] -= parent.scrollTop;
  if (parent.parentNode) {
   parent = parent.parentNode;
  } else {
   parent = null;
  }
 }
 return {x:pos[0], y:pos[1]};
}

使用示例

var pos=getElementPos("divId");
alert("距左边距离"+ pos.x +",距上边距离"+pos.y);

js获取页面元素位置函数(跨浏览器),布布扣,bubuko.com

js获取页面元素位置函数(跨浏览器)

标签:style   使用   os   io   for   cti   html   ar   

原文地址:http://www.cnblogs.com/90nice/p/3877475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!