我正在制作一个 WYSIWYG 编辑器,我需要知道如何让插入符位置正常工作。似乎没有明显的跨平台方法。
我只需要语法。请不要将我指向 Mozilla 开发人员页面;我没有发现它特别有用。 我正在使用内容可编辑的 div。
最佳答案
试试这个
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);
}
关于javascript - 插入符号索引位置跨浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9370197/