Can I find the pixel position of the cursor in ContentEditable?

I want to find the top / left position of the cursor pixel , not the character offset.

The reason I want to do this is because I want to show a small piece of div type next to the cursor (think of the new MS Word floating formatting) that follows the cursor when you type or press. I can use mouse coordinates if the user clicks, but not sure how to do this for input.

Is there a reliable way? If you do not find the top / left position of the cursor, an alternative is to simply find the top position for the line.

Sample code is not 100% necessary if the method works and is well explained.

+4
source share
2 answers

This is actually not an answer, but concepts to think about:

In contenteditable, everything consists of nodes, just like any other HTML, so you can get the position of the node, the problem is where the node is (if it is text, you can be 100 characters inside the node). Therefore, you must create your own single-character nodes.

To get the position as someone of type, you will need to capture the onkeypress event, stop the propagation bubble, take the character they ask for, fill it in a node (maybe span ala a "marker"), and then enter node. Then you calculate the exact position of this range / node by shifting it.

You may have to delete the range and replace it with just the symbol.

There is also a problem that I encountered, if you mess with bubble events, when scrolling is supposed, the caret may go out of the viewport.

Optional, and it might be a little better, instead of messing around with the spread, allow the browser to insert the character into its own, and then immediately insert the unicode character of zero width (invisible) in the span / node before or after, and calculate its position. Then pull out the markers either on the fly or when they stop printing.

Yes, it's dirty, sorry. If anyone has a better way, I'm all ears.

+3
source

try it

var cursorY = window.getSelection().getRangeAt(0).getBoundingClientRect().top; 

cursorY - position of the Y cursor in the window.

A Selection object represents a range of text, the selected user, or the current caret position.

Selection.getRangeAt () returns a range object representing one of the selected ranges.

0
source

Source: https://habr.com/ru/post/1336789/


All Articles