问题
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