JavaScript get page coordinates of closest clicked character

对着背影说爱祢 提交于 2020-01-15 05:25:08

问题


I have a div tag with a bunch of text in it.

<div>Lots of text in here</div>

I am listening for onclick events from the div. I would like to insert a fake text cursor wherever the user clicked in the div. I can easily get what character was clicked with:

var sel = window.getSelection();
sel.focusOffset;

But I don't know how to get the pixel coordinates of that character.


回答1:


The rangy library has a feature that does exactly this - find pixel position of selection. Take a look at this demo: http://rangy.googlecode.com/svn/trunk/demos/position.html

Library home: http://code.google.com/p/rangy/

Once you get the pixel position using rangy, you can dynamically add an absolutely positioned DIV (or reposition an existing DIV) to those coordinates.



来源:https://stackoverflow.com/questions/8611742/javascript-get-page-coordinates-of-closest-clicked-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!