用 Javascript 获取指定页面元素的位置 - top, left, document, Element, 元素, position, 位置

 

 Javascript 获取指定页面元素的位置是一个非常常见的需求,本文介绍的方法能够准确返回一个元素相对于整个文档左上角的坐标,即元素的 top left 的位置,而且能够兼容浏览器,相信对新手非常有用。

 

 

--------------------------------------------------------------

点此浏览示例文件

--------------------------------------------------------------

 

 

Javascript:

 

  1.  
  2. <script language="JavaScript" type="text/javascript">
  3. <!--
  1.  
  1. // 说明:用 Javascript 获取指定页面元素的位置
  2. // 整理:http://www.codebit.cn
  3. // 来源:YUI DOM
  1.  
  1. function getElementPos(elementId) {
  1.  
  1. var ua = navigator.userAgent.toLowerCase();
  2. var isOpera = (ua.indexOf('opera') != -1);
  3. var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof
  1.  
  1. var el = document.getElementById(elementId);
  1.  
  1. if(el.parentNode === null || el.style.display == 'none') 
  1. {
  1. return false;
  1. }
  1.  
  1. var parent = null;
  2. var pos = [];
  1. var box;
  1.  
  1. if(el.getBoundingClientRect)    //IE
  1. {
  1. box = el.getBoundingClientRect();
  1. var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  2. var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
  1.  
  1. return {x:box.left + scrollLeft, y:box.top + scrollTop};
  1. }
  1. else if(document.getBoxObjectFor)    // gecko
  1. {
  1. box = document.getBoxObjectFor(el);
  1. var borderLeft = (el.style.borderLeftWidth)?parseInt(el.style.borderLeftWidth):0;
  1. var borderTop = (el.style.borderTopWidth)?parseInt(el.style.borderTopWidth):0;
  1.  
  1. pos = [box.x - borderLeft, box.y - borderTop];
  1. }
  1. else    // safari & opera
  1. {
  1. pos = [el.offsetLeft, el.offsetTop];
  1. parent = el.offsetParent;
  1. if (parent != el) {
  2. while (parent) {
  1. pos[0] += parent.offsetLeft;
  2. pos[1] += parent.offsetTop;
  3. parent = parent.offsetParent;
  1. }
  1. }
  1. if (ua.indexOf('opera') != -1 
  1. || ( ua.indexOf('safari') != -1 && el.style.position == 'absolute' )) 
  1. {
  1. pos[0] -= document.body.offsetLeft;
  1. pos[1] -= document.body.offsetTop;
  1. } 
  2. }
  1. if (el.parentNode) { parent = el.parentNode; }
  1. else { parent = null; }
  1. while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') 
  1. { // account for any scrolled ancestors
  1. pos[0] -= parent.scrollLeft;
  1. pos[1] -= parent.scrollTop;
  1. if (parent.parentNode) { parent = parent.parentNode; } 
  1. else { parent = null; }
  1. }
  1. return {x:pos[0], y:pos[1]};
  1. }
  1.  
  1. //-->
  1. </script>
  1.  

 

从 <http://www.codebit.cn/pub/html/javascript/tip/get_element_position/> 插入