How can I find the cursor location (X/Y, not line/

2019-03-17 15:30发布

问题:

This question already has an answer here:

  • How do I get the (x, y) pixel coordinates of the caret in text boxes? 3 answers

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:

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.

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.