如何获得包含图像的contenteditable div的插入位置

时间:2016-11-22 17:05:17

标签: javascript contenteditable caret getcaretpos

我有这个contentedittable div

<div contenteditable="true" id="text">minubyv<img src="images/smiley/Emoji Smiley-01.png" class="emojiText" />iubyvt</div>

以下是代码输出的图像说明 enter image description here

所以我想获得div的插入位置,并假设光标位于最后一个字符之后。这是我获得插入位置的代码

function getCaretPosition(editableDiv) {
  var caretPos = 0,
    sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      if (range.commonAncestorContainer.parentNode == editableDiv) {
        caretPos = range.endOffset;
      }
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    if (range.parentElement() == editableDiv) {
      var tempEl = document.createElement("span");
      editableDiv.insertBefore(tempEl, editableDiv.firstChild);
      var tempRange = range.duplicate();
      tempRange.moveToElementText(tempEl);
      tempRange.setEndPoint("EndToEnd", range);
      caretPos = tempRange.text.length;
    }
  }
  return caretPos;
}

var update = function() {
  console.log(getCaretPosition(this));
};
$('#text').on("mousedown mouseup keydown keyup", update);

但问题是它返回6而不是14。插入符号位置在图像后返回0。在这种情况下,我有办法让插入符号位置为14

修改

我还想从插入符号位置开始插入一些元素。所以这是我的功能

selectStart = 0;
var update = function() {
  selectStart = getCaretPosition(this);
};
function insertEmoji(svg){
    input = $('div#text').html();
    beforeCursor = input.substring(0, selectStart);
    afterCursor = input.substring(selectStart, input.length);
    emoji = '<img src="images/smiley/'+svg+'.png" class="emojiText" />';
    $('div#text').html(beforeCursor+emoji+afterCursor);
}

1 个答案:

答案 0 :(得分:8)

请参阅Tim Down's上的Get a range's start and end offset's relative to its parent container回答。

尝试使用他拥有的函数来获取具有嵌套元素的选择索引,如下所示:

&#13;
&#13;
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 update = function() {
  console.log(getCaretCharacterOffsetWithin(this));
};
$('#text').on("mousedown mouseup keydown keyup", update);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="text">minubyv<img src="https://themeforest.net/images/smileys/happy.png" class="emojiText" />iubyvt</div>
&#13;
&#13;
&#13;

我根据Tim Down编写了自己的功能,它的工作方式与你想要的一样。我将treeWalker更改为NodeFilter.ELEMENT_NODE的{​​{1}}过滤器,现在NodeFilter.SHOW_TEXT元素也会在循环中处理。我首先存储<img/>,然后递归所有选择树节点。如果它找到range.startOffset节点,则它只向该位置添加1;如果当前节点元素与我们的img不同,则它会添加该节点的长度。该位置由另一个变量range.startContainer更改,该变量在每个循环中添加到lastNodeLength。最后,当它存在于循环中时,它会将charCount中剩余的内容添加到lastNodeLength,并且我们拥有正确的最终插入位置,包括图像元素。

最终工作代码 (最后返回14,完全按照您应该的方式返回)

&#13;
&#13;
charCount
&#13;
function getCharacterOffsetWithin_final(range, node) {
    var treeWalker = document.createTreeWalker(
        node,
        NodeFilter.ELEMENT_NODE,
        function(node) {
            var nodeRange = document.createRange();
            nodeRange.selectNodeContents(node);
            return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
                NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
        },
        false
    );

    var charCount = 0, lastNodeLength = 0;

    if (range.startContainer.nodeType == 3) {
        charCount += range.startOffset;
    }

    while (treeWalker.nextNode()) {
        charCount += lastNodeLength;
        lastNodeLength = 0;
        
        if(range.startContainer != treeWalker.currentNode) {
            if(treeWalker.currentNode instanceof Text) {
                lastNodeLength += treeWalker.currentNode.length;
            } else if(treeWalker.currentNode instanceof HTMLBRElement ||
                      treeWalker.currentNode instanceof HTMLImageElement /* ||
                      treeWalker.currentNode instanceof HTMLDivElement*/)
            {
                lastNodeLength++;
            }
        }
    }
    
    return charCount + lastNodeLength;
}

var update = function() {
    var el = document.getElementById("text");
    var range = window.getSelection().getRangeAt(0);
    console.log("Caret pos: " + getCharacterOffsetWithin_final(range, el))
};
$('#text').on("mouseup keyup", update);
&#13;
&#13;
&#13;