javascript html要素の座標を取得する

javascript html要素の座標を取得する

javascriptで、getBoundingClientRectメソッドを使って、html要素の座標を取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.114

getBoundingClientRectメソッド使い方

「getBoundingClientRect」メソッドを使用すれば、html要素の座標を取得することが可能です。

<span id="result">座標</span>

<script>

// 上からのY座標
console.log( result.getBoundingClientRect().top )

// 左からのx座標
console.log( result.getBoundingClientRect().left )

// 右からのx座標
console.log( result.getBoundingClientRect().right )

// 下からのY座標
console.log( result.getBoundingClientRect().bottom )

</script>

実行結果

サンプルコード

以下は、
「取得」ボタンをクリックすると、各座標を取得して表示する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  function hoge() {    
   
    // document.getElementById('resultop');を省略
    resulttop.textContent = "top :" + resulttop.getBoundingClientRect().top;
    resultleft.textContent = "left :" + resultleft.getBoundingClientRect().left;
    resultright.textContent = "right :" + resultright.getBoundingClientRect().right;
    resultbottom.textContent = "bottom :" + resultbottom.getBoundingClientRect().bottom;

  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main">

    <h2><span id="resulttop" class="badge bg-primary">上からのY座標</span></h2>
    <h2><span id="resultleft" class="badge bg-primary">左からのx座標</span></h2>
    <h2><span id="resultright" class="badge bg-primary">右からのx座標</span></h2>
    <h2><span id="resultbottom" class="badge bg-primary">下からのY座標</span></h2>

    <button id="btn" type="button" class="btn btn-info">
      取得
    </button>

  </div>
</body>

</html>

座標が取得されていることが確認できます。