我找到了一个解决方案:
JS:
function getCaretPosition(editableDiv) {
var caretPos = 0, containerEl = null, sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement("span");
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint("EndToEnd", range);
caretPos = tempRange.text.length;
}
}
return caretPos;
}
$.fn.selectRange = function (start, end) {
if (!end) end = start;
return this.each(function () {
if (this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
用法:
$('#content').click(function (e) {
var content = $(this);
var editor = $('#editor');
var caret = getCaretPosition(this);
var position = content.offset();
editor.css('left', position.left);
editor.css('top', position.top);
editor.val(content.text());
editor.show();
var mousePosition = { x: e.offsetX, y: e.offsetY };
// here I want to set the #editor caret position at the same place,
// where user clicks the #content (mousePosition variable)
editor.selectRange(caret, caret);
});