javascript - 插入符号索引位置跨浏览器?

标签 javascript caret

我正在制作一个 WYSIWYG 编辑器,我需要知道如何让插入符位置正常工作。似乎没有明显的跨平台方法。

我只需要语法。请不要将我指向 Mozilla 开发人员页面;我没有发现它特别有用。 我正在使用内容可编辑的 div。

source that i looked at

最佳答案

试试这个

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/

相关文章:

html - 我可以更改浏览器中表单/文本区域中闪烁的插入符号吗?

java - 使用 PlainDocument 在 JTextField 中移动插入符号

javascript - 移动 View 中重叠的 Bootstrap 内容

javascript - 当 Node/Express 中的请求已附加某些内容时,需要 Require 语句吗?

javascript - AWS 物联网 : Subscribe to Topic in Browser

javascript - 在纯 Javascript 中按类隐藏元素

javascript - jQuery val() 无法在 Chrome 中使用 Caret 逻辑

javascript - 如何修复 Firefox contenteditable 自动换行?

javascript - Discord 静音命令收到 TypeError : fn is not a function

java - 按下回车后的 JTextArea