Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy tọa độ (coordinates) của mọi link trong trang bằng JavaScript


Dùng element.getBoundingClientRect() để lấy vị trí chính xác (x, y, width, height) so với viewport. offsetWidth/Height chỉ lấy kích thước, không phải tọa độ.

Ví dụ

Lấy tọa độ các link <a>:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Link coordinates</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: green; }
  </style>
</head>
<body>
  <h1>Tọa độ của mọi link trong trang</h1>
  <div class="result"></div>
  <a href="https://google.com">google.com</a>
  <a href="https://facebook.com">facebook.com</a>
  <a href="https://yahoo.com">yahoo.com</a>
  <button class="Btn">LẤY TỌA ĐỘ</button>
  <h3>Nhấn nút để hiển thị vị trí các link</h3>
  <script>
    const resEle = document.querySelector(".result");
    const btn = document.querySelector(".Btn");
    const links = document.querySelectorAll('a');
    btn.addEventListener("click", () => {
      links.forEach((link, i) => {
        const rect = link.getBoundingClientRect();
        resEle.innerHTML += `Link ${i+1}: left=${rect.left.toFixed(0)}, top=${rect.top.toFixed(0)}, width=${rect.width}, height=${rect.height}<br>`;
      });
    });
  </script>
</body>
</html>

Kết quả

Hiển thị tọa độ (left, top) và kích thước (width, height) của từng link so với viewport.

Sửa lỗi code gốc: Code gốc dùng offsetWidth/Height (kích thước) thay vì tọa độ. Đã sửa thành getBoundingClientRect().