Caret index position cross browser?

前提是你 提交于 2019-12-05 04:07:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!