开发者

Pass click event with offset to contentEditable

开发者 https://www.devze.com 2023-02-22 22:42 出处:网络
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.

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 be开发者_如何学Goginning 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消