简体   繁体   中英

Pass click event with offset to contentEditable

I have a div ( .top ) that is on top of another div ( .text ). If .top is clicked it should hide and .text should get editable. I also give .text directly the focus.

Unfortunately the cursor is always at the beginning then. If it would have been clicked directly then the cursor would be were the user has clicked.

Here is a demo .

Is there a way to pass the click event from .top to .text with the correct offset (as this seems to be needed for setting the correct cursor position)?

I have two ideas on this. Firstly avoid the issue by switching classes to change the style of the editable version rather than having two divs, one of which you disable.

The other idea is to attach a click handler in the 'capture phase' rather than the more traditional bubble phase so that the event continues to propagate and the edit box gets the click. I'm not sure right now how to do that in jQuery.

The click event is being fired by the DIV. It doesn't know WHERE the click occurred. To do that you'd have to keep track of mouse events as well. This is not difficult in itself.

From the mouse x,y you can calculate the DIV x,y and transform the coordinates. This also is not difficult.

The problem arises is that there is no direct correlation between the characters in the DIV and the click. To do this you'd basically need to insert an element into the DIV and iterate its position in your text until you match the approximate mouse click position. It will likely not be an exact match since you're not clicking at the start or end of a character exactly.

Then you have to figure out where this is and move the cursor there in code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM