JS 獲取元素的偏移量


獲取元素的偏移量

獲取父級節點

curEle.parentNode

document.parentNode -> null

父級參照物

offsetParent: 父級參照物

在同一個平面中, 最外層的元素是里面所有元素的父級參照物(和HTML層級結構沒有必然的聯系)

一般來說一個頁面中所有的父級參照物都是body
body的父級參照物是null

使用position

想要改變父級參照物需要通過positon定位來進行改變: absolute, relative, fixed 任意一個值都可以把父級參照物進行修改

不能修改的有, static, inherit

offSetTop/ offSetLeft

offSetTop/ offSetLeft, 當前元素(外邊框)距離其父級參照物的(內邊框)偏移距離

獲取距離body的左偏移

求出頁面中任意一個元素(不管它的父級參照物是誰)距離body的左偏移

  • 首先加上自己本身的左偏移
  • 獲取自己的父級參照物P, 把P的左邊框和左偏移都加上
  • 基於當前的P再向上找父級參照物, 找到后依然是累加邊框和其左偏移
  • 一直到父級參照物為null, 已經找到body了

圖示:

代碼

offset: 等同於jQuery中的offset方法, 實現獲取頁面中任意一個元素, 距離body的偏移(包括左偏移和上偏移), 不管當前元素的父級參照物是誰

function offset(curEle) {
      var totallLeft = null,
        totalTop = null,
        par = curEle.offsetParent;
      totallLeft += curEle.offsetLeft;
      totalTop += curEle.offsetTop;
      while (par) {
        totallLeft += par.clientLeft;
        totalTop += par.clientTop;
        totallLeft += par.offsetLeft;
        totalTop += par.offsetTop;
        par = par.offsetParent;
      }
      return {
        left: totallLeft,
        top: totalTop,
      };
    }
兼容

在標准的IE8瀏覽器中, 我們使用offsetLeft/ offsetTop, 其實是把父級參照物的邊框已經算在內了, 所以我們不需要自己再單獨的加邊框了

以下是兼容IE8瀏覽器的代碼
 function offset(curEle) {
      var totallLeft = null,
        totalTop = null,
        par = curEle.offsetParent;
      totallLeft += curEle.offsetLeft;
      totalTop += curEle.offsetTop;
      while (par) {
        if (navigator.userAgent.indexOf("MSIE 8.0") === -1) {
          //不是標准的IE8瀏覽器, 我們才累加邊框
          totallLeft += par.clientLeft;
          totalTop += par.clientTop;
        }
        totallLeft += par.offsetLeft;
        totalTop += par.offsetTop;
        par = par.offsetParent;
      }
      return {
        left: totallLeft,
        top: totalTop,
      };
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM