zoukankan      html  css  js  c++  java
  • 获取元素位置信息:getBoundingClientRect

     一个神奇的方法。

    一、历史

    偷个懒,上个传送门:http://www.cnblogs.com/2050/archive/2012/02/01/2335211.html

    二、介绍

    DOM元素方法,返回一个TextRectangle对象,包含top,left,bottom,right,width,height六个属性,表示元素相对于浏览器显示区域的四个偏移量和元素自身的宽高,都是number,表示的是像素值。

    document.body.getBoundingClientRect().top      // 0
    document.body.getBoundingClientRect().width    // 600

    三、兼容性

    getBoundingClientRect方法最先在IE5中出现,后来被W3C接纳成为标准。目前IE5.5+、Firefox 3.5+、Chrome 4+、Safari 4.0+、Opara 10.10+等浏览器均支持该方法,兼容性几乎完美。

    但老版本浏览器只有top,left,bottom,right四个属性,没有width和height,不过这两个属性可以算出来,所以兼容写法可以这么写:

    var ro = object.getBoundingClientRect();
    var Top = ro.top;
    var Bottom = ro.bottom;
    var Left = ro.left;
    var Right = ro.right;
    var Width = ro.width||Right - Left;
    var Height = ro.height||Bottom - Top;

    四、基友

    还有一个类似的方法是getClientRects,不过一般用getBoundingClientRect就够了。

    具体可见:http://blog.csdn.net/freshlover/article/details/8985887

    五、用途

    配合scrollTop和scrollLeft可以获取到相对页面的位置:

    var X = this.getBoundingClientRect().left+document.documentElement.scrollLeft;
    var Y = this.getBoundingClientRect().top+document.documentElement.scrollTop;

    这两个属性会有些兼容问题,具体可见:http://www.cnblogs.com/purplefox2008/archive/2010/09/06/1818873.html

  • 相关阅读:
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
    iOS
  • 原文地址:https://www.cnblogs.com/ccforeverd/p/4031790.html
Copyright © 2011-2022 走看看