使用光标位置获取元素内的文本

Get text inside element using cursor position?

本文关键字:文本 元素 获取 光标 位置      更新时间:2023-09-26

在我的项目中,我正在使用伟大而有用的jQuery TextRange插件。我在文本区域的顶部有一个突出显示的div,我必须知道用户正在编辑的实际元素是什么。为了更好地理解,我将在下面使用很多例子。

在我的项目中,如果我在文本区域上有以下文本:

Text that doesn't matter #this_matter and #this_too

我的亮点div 中有这样的东西:

"Text that doesn't matter <b>#this_matter</b> and #this_too</b>"
<小时 />

一切都很好,但是...

我需要知道我正在编辑的"主题标签"是什么。所以我认为使用位置来解决这个问题,但正如你将看到的,我有一些问题。在我的文本区域中,我使用以下方法获取光标位置:

input = $('#post-input')
var cursorPosition = input.textrange('get','position')

有了这些信息,我需要知道我正在编辑的主题标签是什么。假设|是光标在文本区域中位置的符号,因此:

"Text that doesn't matter #this_matter and #this|_too"

必须返回<b>#this_too</b>元素,因为这是实际的主题标签。再比如:

 "Text that doesn't matter #|this_matter and #this_too"

必须返回<b>#this_matter</b>

毕竟,我如何返回带有光标位置信息的正确元素?

你可以

使用document.elementFromPoint

document.elementFromPoint(event.clientX, event.clientY);