kembali ke pelajaran
Materi ini hanya tersedia dalam bahasa berikut: عربي, English, Español, Français, Italiano, 日本語, Русский, Türkçe, Українська, 简体中文. Tolong, bantu kami menerjemahkan ke dalam Indonesia.

Find window coordinates of the field

pentingnya: 5

In the iframe below you can see a document with the green “field”.

Use JavaScript to find window coordinates of corners pointed by with arrows.

There’s a small feature implemented in the document for convenience. A click at any place shows coordinates there.

Your code should use DOM to get window coordinates of:

  1. Upper-left, outer corner (that’s simple).
  2. Bottom-right, outer corner (simple too).
  3. Upper-left, inner corner (a bit harder).
  4. Bottom-right, inner corner (there are several ways, choose one).

The coordinates that you calculate should be the same as those returned by the mouse click.

P.S. The code should also work if the element has another size or border, not bound to any fixed values.

Buka sandbox untuk tugas tersebut.

Outer corners

Outer corners are basically what we get from elem.getBoundingClientRect().

Coordinates of the upper-left corner answer1 and the bottom-right corner answer2:

let coords = elem.getBoundingClientRect();

let answer1 = [coords.left, coords.top];
let answer2 = [coords.right, coords.bottom];

Left-upper inner corner

That differs from the outer corner by the border width. A reliable way to get the distance is clientLeft/clientTop:

let answer3 = [coords.left + field.clientLeft, coords.top + field.clientTop];

Right-bottom inner corner

In our case we need to substract the border size from the outer coordinates.

We could use CSS way:

let answer4 = [
  coords.right - parseInt(getComputedStyle(field).borderRightWidth),
  coords.bottom - parseInt(getComputedStyle(field).borderBottomWidth)
];

An alternative way would be to add clientWidth/clientHeight to coordinates of the left-upper corner. That’s probably even better:

let answer4 = [
  coords.left + elem.clientLeft + elem.clientWidth,
  coords.top + elem.clientTop + elem.clientHeight
];

Buka solusi di kotak pasir.