我怎么能在一个可编辑的div中存储插入位置?

时间:2016-11-08 16:21:28

标签: javascript jquery html5 google-chrome contenteditable

我已经转换了一个普通的textarea,它先前存储了用户插入位置,并在重新打开Chrome扩展程序时将其返回。我现在已将文本区域更改为可编辑的div以启用基本文本格式,但插入位置存储不起作用。

我目前有工作代码将插入位置存储在文本区域中,但我现在需要找出我需要更改的内容,以便在可编辑的div中工作。

(function($) {
$.fn.caret = function(pos) {
    var target = this[0];
    var isContentEditable = target.contentEditable === 'true';
    if (arguments.length == 0) {
        if (window.getSelection) {
            if (isContentEditable) {
                target.focus();
                var range1 = window.getSelection().getRangeAt(0),
                    range2 = range1.cloneRange();
                range2.selectNodeContents(target);
                range2.setEnd(range1.endContainer, range1.endOffset);
                return range2.toString().length;
            }
            return target.selectionStart;
        }
        if (document.selection) {
            target.focus();
            if (isContentEditable) {
                var range1 = document.selection.createRange(),
                    range2 = document.body.createTextRange();
                range2.moveToElementText(target);
                range2.setEndPoint('EndToEnd', range1);
                return range2.text.length;
            }
            var pos = 0,
                range = target.createTextRange(),
                range2 = document.selection.createRange().duplicate(),
                bookmark = range2.getBookmark();
            range.moveToBookmark(bookmark);
            while (range.moveStart('character', -1) !== 0) pos++;
            return pos;
        }
        return 0;
    }
    if (pos == -1)
        pos = this[isContentEditable ? 'text' : 'val']().length;
    if (window.getSelection) {
        if (isContentEditable) {
            target.focus();
            window.getSelection().collapse(target.firstChild, pos);
        } else
            target.setSelectionRange(pos, pos);
    } else if (document.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(target);
        range.moveStart('character', pos);
        range.collapse(true);
        range.select();
    }
    if (!isContentEditable)
        target.focus();
    return pos;
}
})(jQuery)

1 个答案:

答案 0 :(得分:2)

看一下这个片段(归功于this answer,我在这里复制了小提琴):

此代码侦听mouseup和keyup事件以重新计算插入符的位置。你可以将它存储在这些点上。



function getCaretCharacterOffsetWithin(element) {
  var caretOffset = 0;
  var doc = element.ownerDocument || element.document;
  var win = doc.defaultView || doc.parentWindow;
  var sel;
  if (typeof win.getSelection != "undefined") {
    sel = win.getSelection();
    if (sel.rangeCount > 0) {
      var range = win.getSelection().getRangeAt(0);
      var preCaretRange = range.cloneRange();
      preCaretRange.selectNodeContents(element);
      preCaretRange.setEnd(range.endContainer, range.endOffset);
      caretOffset = preCaretRange.toString().length;
    }
  } else if ((sel = doc.selection) && sel.type != "Control") {
    var textRange = sel.createRange();
    var preCaretTextRange = doc.body.createTextRange();
    preCaretTextRange.moveToElementText(element);
    preCaretTextRange.setEndPoint("EndToEnd", textRange);
    caretOffset = preCaretTextRange.text.length;
  }
  return caretOffset;
}

var lastCaretPos = 10;

function showCaretPos() {
  /* You could store the position when you call this function */
  var el = document.getElementById("test");
  lastCaretPos = getCaretCharacterOffsetWithin(el);
  var caretPosEl = document.getElementById("caretPos");
  caretPosEl.innerHTML = "Caret position: " + lastCaretPos;
}

function restoreCaretPos() {
  var node = document.getElementById("test");
  node.focus();
  var textNode = node.firstChild;
  var range = document.createRange();
  range.setStart(textNode, lastCaretPos);
  range.setEnd(textNode, lastCaretPos);
  var sel = window.getSelection();
  sel.removeAllRanges();
  sel.addRange(range);
}

document.getElementById("test").onkeyup = showCaretPos;
document.getElementById("test").onmouseup = showCaretPos;
document.getElementById("button").onclick = restoreCaretPos;

<div id="test" contenteditable="true">This is an editable div</div>
<div id="caretPos">Caret position: 10</div>
<input type="button" id="button" value="restore caret" />
&#13;
&#13;
&#13;