问题
I'm making a WYSIWYG editor, and I need to know how to get caret position working. It appears that there's no obvious way of doing it cross-platform.
I just need the syntax. Please don't point me towards the Mozilla developer page; I didn't find it particularly useful. I'm using a content editable div.
source that i looked at
回答1:
try this
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
来源:https://stackoverflow.com/questions/9370197/caret-index-position-cross-browser