首页 > 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学习者快速成长!