>  기사  >  웹 프론트엔드  >  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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.