首頁 > web前端 > js教程 > 主體

如何用JavaScript取得滑鼠遊標下的單字?

Patricia Arquette
發布: 2024-10-26 07:06:03
原創
280 人瀏覽過

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

如何使用JavaScript 檢索遊標下方的單字

確定滑鼠遊標懸停的單字是文字的一項基本任務基於的應用程式。假設你有一個 HTML 頁面,其中有一段文字:

<code class="html"><p> some long text </p></code>
登入後複製

如何辨識遊標位於「文字」一詞上方?本文介紹了一個專門針對 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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!