ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScriptでカーソル下の単語を特定するにはどうすればよいですか?

JavaScriptでカーソル下の単語を特定するにはどうすればよいですか?

Linda Hamilton
Linda Hamiltonオリジナル
2024-10-24 17:27:02937ブラウズ

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。