我尝试了以下stackoverflow中的代码:
Get caret (cursor) position in contentEditable area containing HTML content
但是我想在onKeyDown而不是onKeyUp上做(因此对用户来说似乎更快),但是chrome似乎弄乱了它返回的偏移量。有人可以解释这种行为吗?
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
function showCaretPos() {
var el = document.getElementById("test");
var caretPosEl = document.getElementById("caretPos");
caretPosEl.innerHTML = "Caret position: " + getCaretCharacterOffsetWithin(el);
}
document.body.onkeydown = showCaretPos;
document.body.onmousedown = showCaretPos;
要重现,只需在第一个字母前单击并按键盘上的(右)键转到第一个元素,但由于某种原因它保持为0。这是一个错误吗?