问题
I have a contenteditable div and I need to get the x and y position in pixels of the current selection (i.e. of the caret). What I have now is a method which gets the selection relative to the window i.e. window.getSelection()
. What I found are methods which return the position in offsets relative to the div node.
Do you have any ideas about this or maybe a plugin? I found plugins that return cursor positions relative to a text area but unfortunately not for a content editable div.
Here is the code I have right now:
function getSelectionCoords() {
var sel = document.selection, range;
var x = 0, y = 0;
if (sel) {
if (sel.type != "Control") {
range = sel.createRange();
range.collapse(true);
x = range.boundingLeft;
y = range.boundingTop;
}
} else if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects()) {
range.collapse(true);
var rect = range.getClientRects()[0];
x = rect.left;
y = rect.top;
}
}
}
return { x: x, y: y };
}
Thanks for your help.
来源:https://stackoverflow.com/questions/16524842/get-x-y-position-of-selection-relative-to-a-contenteditable-div