如何在HTML文本区域中找到光标位置(X / Y,而不是行/列)?

问题描述:

我想在< textarea> 中显示一个下拉列表,以帮助用户键入某些内容。你知道这从当前IDEs作为代码完成。当您开始输入内容时,弹出窗口将显示在当前光标/插入位置的右侧,您可以使用箭头键来完成文本输入。

I'd like to display a dropdown list in a <textarea> to assist the user in typing certain things. You know this from current IDEs as code completion. As you start typing something, a popup will appear right a the current cursor/caret location and you can navigate it using arrow keys to complete your text input.

我知道如何获取文本中的光标位置字符串(即光标位置的字符索引),但我不知道如何获得X / Y坐标(像 offsetWidth offsetHeight 元素中的光标所在位置,以便我可以将我的列表元素放在那里。

I know how to get the cursor position in the text string (i.e. the character index of the cursor position) but I do not know how to get the X/Y coordinates (something like offsetWidth and offsetHeight) of the cursor inside the <textarea> element so that I can position my list element there. Is that possible in HTML/JavaScript, and how would it work?

使用可编辑的html输入(在iframe中, a href =http://ckeditor.com/demo =nofollow> CKeditor 或富文本编辑器或更好: jsfiddle )您可以在插入位置插入一个空的span元素并获取该元素的位置以显示您的下拉菜单。

With an editable html input (in an iframe like CKeditor or Rich Text Editor or even better: jsfiddle) you could insert an empty span element at the caret position and get the position of that element to display your dropdown.

这可能看起来很复杂,但我无法想到任何其他方式。

It might seem complex but I can't think of any other way to do this.

一些额外的可能性,当用于代码编辑器,你可以颜色编码的文本和格式代码像jsfiddle,甚至可以建立一些类型的代码自动完成关键字等。

It has some extra possibilities when used for a code editor, you could color-code the text and format code like jsfiddle does, and maybe even build some kind of code-auto-complete for keywords etc.