精确获取页面元素的位置

来源于: http://www.cnblogs.com/rubylouvre/archive/2009/09/08/1562444.html

基本方法是用目前浏览器都支持的getBoundingClientRect方法(IE率先提供的方法),然后对html或body的可能误差做修正,从jQuery中提取的函数:

var getCoords = function(el){
  var box = el.getBoundingClientRect(),
  doc = el.ownerDocument,
  body = doc.body,
  html = doc.documentElement,
  clientTop = html.clientTop || body.clientTop || 0,
  clientLeft = html.clientLeft || body.clientLeft || 0,
  top  = box.top  + (self.pageYOffset || html.scrollTop  ||  body.scrollTop ) - clientTop,
  left = box.left + (self.pageXOffset || html.scrollLeft ||  body.scrollLeft) - clientLeft
  return { 'top': top, 'left': left };
};

http://cssor.com/accurately-obtain-the-position-of-page-elements.html

参与评论

电子邮件地址不会被公开。 必填项已用*标注

*

全部分类
Books(4)code(7)database(6)html&css(24)java(11)JavaScript(49)jQuery(24)linux(20)python(1)React(1)share(1)soft(4)solution(53)thinking(17)vim(9)WordPress(8)前端优化(12)拓展(33)服务器(33)移动开发(4)自然(22)