ホームページ  >  記事  >  ウェブフロントエンド  >  jsのgetBoundingClientRectの機能は何ですか?

jsのgetBoundingClientRectの機能は何ですか?

亚连
亚连オリジナル
2018-06-08 14:49:491945ブラウズ

この記事では主に js における getBoundingClientRect の役割と互換性ソリューションの詳細な説明を紹介し、参考にさせていただきます。

1. getBoundingClientRect

getBoundingClientRect の役割は、ウィンドウに対する HTML 要素の位置セットを取得するために使用されます。

object.getBoundingClientRect(); を実行すると、要素の top、right、bottom、left、width、height 属性がオブジェクトとして返されます。

getBoundingClientRect()

このメソッドは、left、top、right、bottom の 4 つのプロパティを含む長方形のオブジェクトを返します。要素の各辺とページの上辺および左辺との間の距離をそれぞれ表します。

var box=document.getElementById('box'); // 获取元素

alert(box.getBoundingClientRect().top); // 元素上边距离页面上边的距离

alert(box.getBoundingClientRect().right); // 元素右边距离页面左边的距离

alert(box.getBoundingClientRect().bottom); // 元素下边距离页面上边的距离

alert(box.getBoundingClientRect().left); // 元素左边距离页面左边的距离

2. getBoundingClientRect

のup、down、left、rightの属性値の説明 主に左と下について説明する必要があります。左は右側から左端までの距離を指します。底とはページの下端から上端までの距離を指します。

写真を見てください:

3. ブラウザの互換性

ie5 以上をサポートできますが、修正する必要がある点がいくつかあります。

IE67 の左と上は 2px 小さくなります。幅、高さの属性はありません。

4. getBoundingClientRect を使用して、ウィンドウに対する HTML 要素の位置セットを取得するメソッドを作成します

<p id="test" style="width: 100px; height: 100px; background: #ddd;"></p>
<script>
 function getObjXy(obj){
  var xy = obj.getBoundingClientRect();
  var top = xy.top-document.documentElement.clientTop+document.documentElement.scrollTop,//document.documentElement.clientTop 在IE67中始终为2,其他高级点的浏览器为0
   bottom = xy.bottom,
   left = xy.left-document.documentElement.clientLeft+document.documentElement.scrollLeft,//document.documentElement.clientLeft 在IE67中始终为2,其他高级点的浏览器为0
   right = xy.right,
   width = xy.width||right - left, //IE67不存在width 使用right - left获得
   height = xy.height||bottom - top;

  return {
   top:top,
   right:right,
   bottom:bottom,
   left:left,
   width:width,
   height:height
  }
 }

 var test = getObjXy(document.getElementById(&#39;test&#39;));
 alert("top:" + test.top + ", right:" + test.right + ", bottom:" + test.bottom + ", left:" + test.left);
</script>

上記は、将来皆さんのお役に立てれば幸いです。

関連記事:

JSの数値型(詳細なチュートリアル)

AngularでブラウザプラグインBatarangを使用する方法

vueでのプリロードウォッチの使用法

以上がjsのgetBoundingClientRectの機能は何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。