如何在HTML textarea中找到光标位置(X / Y,而不是行/列)? [重复]

时间:2022-06-08 22:54:51

This question already has an answer here:

这个问题在这里已有答案:

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.

我想在

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?

我知道如何在文本字符串中获取光标位置(即光标位置的字符索引),但我不知道如何在

1 个解决方案

#1


2  

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.

使用可编辑的html输入(在像CKeditor或Rich Text Editor这样的iframe中,甚至更好:jsfiddle),您可以在插入位置插入一个空的span元素,并获取该元素的位置以显示您的下拉列表。

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

这可能看起来很复杂,但我想不出有任何其他方法可以做到这一点。

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.

当用于代码编辑器时,它有一些额外的可能性,你可以像jsfiddle一样对文本和格式代码进行颜色编码,甚至可以构建某种代码 - 自动完成关键字等。

#1


2  

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.

使用可编辑的html输入(在像CKeditor或Rich Text Editor这样的iframe中,甚至更好:jsfiddle),您可以在插入位置插入一个空的span元素,并获取该元素的位置以显示您的下拉列表。

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

这可能看起来很复杂,但我想不出有任何其他方法可以做到这一点。

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.

当用于代码编辑器时,它有一些额外的可能性,你可以像jsfiddle一样对文本和格式代码进行颜色编码,甚至可以构建某种代码 - 自动完成关键字等。