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

JavaScript でマウス カーソルの下に単語を表示するにはどうすればよいですか?

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-26 07:06:03281ブラウズ

How to Get the Word Under the Mouse Cursor with JavaScript?

JavaScript でカーソルの下の単語を取得する方法

マウス カーソルが置かれている単語を判断することは、テキストにとって重要なタスクですベースのアプリケーション。次のようなテキストの段落を含む HTML ページがあるとします。

<code class="html"><p> some long text </p></code>

カーソルが「text」という単語の上に位置していることをどのように識別できるでしょうか?この記事では、Chrome (および場合によっては Firefox) に特化したソリューションを紹介します。

JavaScript 実装:

<code class="javascript">function getWordAtPoint(elem, x, y) {
  if (elem.nodeType == elem.TEXT_NODE) {
    // Create a range and position it within the element's text content
    var range = elem.ownerDocument.createRange();
    range.selectNodeContents(elem);

    // Initialize position variables
    var currentPos = 0;
    var endPos = range.endOffset;

    // Iterate through the text content
    while (currentPos + 1 < endPos) {
      // Update the range to select a single character
      range.setStart(elem, currentPos);
      range.setEnd(elem, currentPos + 1);

      // Check if the character's bounding rectangle contains the cursor position
      if (
        range.getBoundingClientRect().left <= x &&
        range.getBoundingClientRect().right >= x &&
        range.getBoundingClientRect().top <= y &&
        range.getBoundingClientRect().bottom >= y
      ) {
        // Expand the range to select the word
        range.expand("word");
        var ret = range.toString();
        range.detach();
        return ret;
      }

      // Advance the current position
      currentPos += 1;
    }
  } else {
    // For elements with child nodes (e.g., <p>, <div>), iterate through their children
    for (var i = 0; i < elem.childNodes.length; i++) {
      // Create a range and position it within the child node's text content
      var range = elem.childNodes[i].ownerDocument.createRange();
      range.selectNodeContents(elem.childNodes[i]);

      // Check if the child node's bounding rectangle contains the cursor position
      if (
        range.getBoundingClientRect().left <= x &&
        range.getBoundingClientRect().right >= x &&
        range.getBoundingClientRect().top <= y &&
        range.getBoundingClientRect().bottom >= y
      ) {
        // Recursively call getWordAtPoint on the child node
        range.detach();
        return getWordAtPoint(elem.childNodes[i], x, y);
      } else {
        range.detach();
      }
    }
  }

  return null;
}</code>

使用法:

mousemove イベントのイベント ハンドラーでは、次のように getWordAtPoint() 関数を利用できます:

<code class="javascript">getWordAtPoint(e.target, e.x, e.y);</code>

以上がJavaScript でマウス カーソルの下に単語を表示するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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