如何在光标下获取单词?

art*_*ave 5 javascript jquery

假设有一个mousestop事件附加到整个文档,当鼠标停止移动时,找出光标下的确切单词(如果有任何文本)的最佳方法是什么?

我可以从事件处理程序中获取底层(jQuery)元素$(document.elementFromPoint(e.clientX, e.clientY))- 但接下来是什么?

到目前为止,我的想法是将hit元素中的所有文本节点替换为其中每个单词都包含在DOM元素中的副本(不知道哪一个),然后$(document.elementFromPoint(e.clientX, e.clientY))再次调用以获取仅包含鼠标下单词的元素.
但这似乎是一个复杂的计划,我想知道我是否遗漏了一些更简单的东西.

art*_*ave 2

好吧,到目前为止还没有什么神奇的技巧,所以这是一个沉闷无聊(但有效)的解决方案:

  $(document.body).mousemove(function(e){

    var onmousestop = function() {
      function getHitWord(hit_elem) {
        var hit_word = '';
        hit_elem = $(hit_elem);

        //text contents of hit element
        var text_nodes = hit_elem.contents().filter(function(){
          return this.nodeType == Node.TEXT_NODE && this.nodeValue.match(/[a-zA-Z]{2,}/)
        });

        //bunch of text under cursor? break it into words
        if (text_nodes.length > 0) {
          var original_content = hit_elem.clone();

          //wrap every word in every node in a dom element
          text_nodes.replaceWith(function(i) {
            return $(this).text().replace(/([a-zA-Z-]*)/g, "<word>$1</word>")
          });

          //get the exact word under cursor
          var hit_word_elem = document.elementFromPoint(e.clientX, e.clientY);

          if (hit_word_elem.nodeName != 'WORD') {
            console.log("missed!");
          }
          else  {
            hit_word = $(hit_word_elem).text();
            console.log("got it: "+hit_word);
          }

          hit_elem.replaceWith(original_content);
        }

        return hit_word;
      }

      var hit_word = getHitWord(document.elementFromPoint(e.clientX, e.clientY));
      ...
    }
  }
Run Code Online (Sandbox Code Playgroud)

还有一些其他的微妙之处(比如事件“降噪”、保持替换的 dom 上下文(比如选择)等等),但你明白了。

在这里您可以了解如何设置 mousestop 事件。

编辑:

在 IE 中制作自定义 html 元素可能并不那么困难(谁会想到呢?)。在这里查看更多信息。