最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Caret index position cross browser? - Stack Overflow

programmeradmin6浏览0评论

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

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

Share Improve this question edited Nov 21, 2019 at 22:25 vsync 131k59 gold badges340 silver badges423 bronze badges asked Feb 20, 2012 at 23:51 officegunnerofficegunner 971 silver badge9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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);
}
发布评论

评论列表(0)

  1. 暂无评论