如何在光标下获取单词?

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

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

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

好吧,到目前为止还没有任何魔术技巧,所以这里是沉闷乏味(但仍在工作)的解决方案:

  $(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, "$1") }); //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)); ... } } 

其他细微之处很少(比如事件’降噪’,保持替换dom上下文(例如选择)等等),但你明白了。

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

编辑:

制作自定义html元素可能不是IE中的那种前沿(谁会想到?)。 在这里查看更多。

我没有任何代码,但也许这可能有点帮助:

  1. 当光标处于空闲状态时,获取坐标
  2. 在上面的坐标中搜索页面中的元素
  3. 使用var s = getElementById('ElementIDFoundinStepAbove').innerHTML;

这似乎是一种相当合理的方法,但是,我不知道这是否可能。


编辑:

我刚刚在S / O上找到这篇文章:

2444430

我希望这有帮助。

🙂

贾森