ElementFromPoint Finds The Topmost Element

elementFromPoint answers which element owns a viewport coordinate, and an overlay intercepts hits until it opts out with pointer-events none.

TypescriptData Integrity

Code

typescriptsnippet
39 lines
// elementFromPoint 按视口坐标返回命中元素;遮挡物会拦截命中
const stage = document.createElement('div');
stage.style.position = 'relative';
stage.style.width = '160px';
stage.style.height = '80px';

const save = document.createElement('button');
save.textContent = 'save';
save.style.position = 'absolute';
save.style.inset = '0';
stage.append(save);
document.body.append(stage);

function hitLabelAt(cx: number, cy: number): string {
  const hit = document.elementFromPoint(cx, cy);
  if (!hit) return 'outside viewport';
  return hit === save ? 'button:save' : hit.tagName.toLowerCase();
}

// 用目标元素自身的几何中心作为命中坐标,避免手写视口数字
const box = save.getBoundingClientRect();
const cx = box.left + box.width / 2;
const cy = box.top + box.height / 2;
console.log('bare button hit:', hitLabelAt(cx, cy));

// 盖一个遮罩:命中变成遮罩元素,这就是点击被拦截的机制
// CSS 长度必须带单位——无单位数值会被 CSSOM 静默丢弃
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.left = `${box.left}px`;
overlay.style.top = `${box.top}px`;
overlay.style.width = `${box.width}px`;
overlay.style.height = `${box.height}px`;
document.body.append(overlay);
console.log('with overlay hit:', hitLabelAt(cx, cy));

// 遮罩声明 pointer-events: none 后,命中穿透回下层按钮
overlay.style.pointerEvents = 'none';
console.log('pointer-events none:', hitLabelAt(cx, cy));

The hit-test question

elementFromPoint(cx, cy) returns the topmost element at a viewport coordinate. The bare run centers the coordinates on save.getBoundingClientRect(), so bare button hit: prints button:save.

The overlay intercepts

A fixed-position div is sized to the button’s rect — left/top/width/height assigned with px units, because unitless numbers are silently dropped by CSSOM and would leave the overlay at 0×0. With the overlay in place, with overlay hit: prints div: the overlay owns the point.

Opting out with pointer-events

Setting overlay.style.pointerEvents = ‘none’ makes hit-testing skip the overlay, so pointer-events none: prints button:save again — the standard mechanism behind click-through layers.

Interactive Tools for This Topic

FAQ

Why must the overlay's left/top/width/height include px units?
CSS length values are invalid without units and CSSOM silently discards the assignment, leaving the overlay unsized at 0×0 where it can never intercept the hit.
What does pointer-events: none change about elementFromPoint?
Hit-testing skips the element entirely, so the query falls through to the underlying button — the same rule browsers apply to real clicks.