getBoundingClientRect()がよくわからない

uupaa2008-01-26

getBoundingClientRect()

  1. http://msdn2.microsoft.com/en-us/library/ms536433.aspx
  2. http://developer.mozilla.org/ja/docs/DOM:element.getBoundingClientRect

IE5+,Firefox3+,Opera9.5+で使用可能なメソッド。CSSのボーダーボックスのサイズを取得できるらしいが、
http://msdn2.microsoft.com/en-us/library/ms536433.aspx の例を見ると、
idBeige.style.height を求める方法が、widthのソレと違いすぎる。

    rcts = obj.getClientRects();

    // set the rendering properties for the yellow DIV
    cdTop    = rcts[keyCount].top    + idBody.scrollTop;
    cdLeft   = rcts[keyCount].left   + idBody.scrollLeft;
    cdRight  = rcts[keyCount].right  + idBody.scrollLeft;
    cdBottom = rcts[keyCount].bottom + idBody.scrollTop;
    idYellow.style.top = cdTop;
    idYellow.style.width = (cdRight-cdLeft) - 5;
    idYellow.style.display = 'inline';
    idYellow.style.border = "1px solid red";

    // set the rendering properties for the beige DIV
    bndTop   = obj.getBoundingClientRect().top   + idBody.scrollTop;
    bndLeft  = obj.getBoundingClientRect().left  + idBody.scrollLeft;
    bndRight = obj.getBoundingClientRect().right + idBody.scrollLeft;
    bndBottom= obj.getBoundingClientRect().bottom + idBody.scrollTop;

    idBeige.style.top = bndTop;
    idBeige.style.width = (bndRight-bndLeft) - 5;
// ▼▼▼▼
    idBeige.style.height = cdTop - bndTop;
// ▲▲▲▲

どーも君の箇所をいじったら動かなくなったんが。添付画像はその時の。

// ▼▼▼▼
    idBeige.style.height = (bndBottom-bndTop) - 5;
// ▲▲▲▲

解決したら続きを書きます。

あと、left,topが2px多いってバグを10年以上放置ってのはいただけない。
left,topが常に2px多いのはIE5の話で、IE5.5以上では2pxずれていませんでした。
ただし、IE6以降でもparentNodeがdocument.bodyの場合は x,yから-2px引く必要があります。
IE5+, Firefox3+, Opera9.5+で getBoundingClientRect() は使用可能ですが、-2px 引く必要があるのはIEだけです。