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

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

Linda Hamilton
發布: 2024-10-24 17:27:02
原創
936 人瀏覽過

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中文網其他相關文章!

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