CaretPosition: getClientRect() 方法

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

CaretPosition 介面的 getClientRect() 方法返回插入符範圍的客戶端矩形。

語法

js
getClientRect()

引數

無。

返回值

一個 DOMRect 物件。

示例

獲取插入符的螢幕位置

html
<input aria-label="text field" value="Click inside this input field" />
js
document.querySelector("input").addEventListener("click", (event) => {
  const x = event.clientX;
  const y = event.clientY;

  const caret = document.caretPositionFromPoint?.(x, y);
  if (!caret) {
    log("Not supported");
    return;
  }

  const rect = caret.getClientRect();

  log(`Caret bounding rect: ${JSON.stringify(rect)}`);
  log(`Caret is at (${rect.x.toFixed(2)}, ${rect.y.toFixed(2)})`);
});

規範

規範
CSSOM 檢視模組
# dom-caretposition-getclientrect

瀏覽器相容性

另見