首页 > div编辑器获取光标的位置

div编辑器获取光标的位置

如何获取光标的位置
只适配webkit

<div id="content" style="border: 1px solid #f1f1f1;" contenteditable="true"></div>

我记得Selection对象还有Range对象应该能获取到,详细的你可以查一下MDN


如果是要获取的是光标偏移了多少个文字的话,可以通过 selectionStart 属性来获取,webkit 系的浏览器都支持这一属性。
摘一个 stackoverflow 上的栗子:

/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.value.length.
*/
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;
}

http://ichord.github.io/Caret.js/

【热门文章】
【热门文章】