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