首頁  >  文章  >  web前端  >  JavaScript中如何確定遊標下的單字?

JavaScript中如何確定遊標下的單字?

Linda Hamilton
Linda Hamilton原創
2024-10-24 17:27:02941瀏覽

How to Determine the Word Under the Cursor in JavaScript?

在JavaScript 中確定遊標所在的單字

問題:

給定一個包含文字的HTML 頁面,如何確定遊標所在的當前懸停在?

解決方案:

對於支持 Shadow DOM 的瀏覽器(例如 Chrome)

<code class="js">function getWordAtPoint(elem, x, y) {
  if (elem.nodeType === elem.TEXT_NODE) {
    // Create a range encompassing the element and determine offsets
    let range = elem.ownerDocument.createRange();
    range.selectNodeContents(elem);
    let currentPos = 0;
    let endPos = range.endOffset;

    // Iterate through the characters until finding the one under the cursor
    while (currentPos + 1 < endPos) {
      range.setStart(elem, currentPos);
      range.setEnd(elem, currentPos + 1);
      let boundingClientRect = range.getBoundingClientRect();

      if (
        boundingClientRect.left <= x &&
        boundingClientRect.right >= x &&
        boundingClientRect.top <= y &&
        boundingClientRect.bottom >= y
      ) {
        // Expand to word boundaries and return the text
        range.expand("word");
        let result = range.toString();
        range.detach();
        return result;
      }

      currentPos += 1;
    }
  } else {
    // Recursively check child nodes
    for (let i = 0; i < elem.childNodes.length; i++) {
      range = elem.childNodes[i].ownerDocument.createRange();
      range.selectNodeContents(elem.childNodes[i]);

      // Check if child node is under the cursor
      if (
        range.getBoundingClientRect().left <= x &&
        range.getBoundingClientRect().right >= x &&
        range.getBoundingClientRect().top <= y &&
        range.getBoundingClientRect().bottom >= y
      ) {
        range.detach();
        // Recursively search the child node
        return getWordAtPoint(elem.childNodes[i], x, y);
      } else {
        range.detach();
      }
    }
  }

  return null;
}</code>

用法示例:

<code class="js">document.addEventListener("mousemove", (e) => {
  let word = getWordAtPoint(e.target, e.x, e.y);
  console.log("Word under cursor:", word);
});</code>

以上是JavaScript中如何確定遊標下的單字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn