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

how to get the caret position of a contenteditable div which contains images

我有这个内容可编辑div

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

这是代码输出的图像描述

所以我想获得 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);

但问题是它returns 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);
}

参见 Tim Down's answer on Get a range's start and end offset's relative to its parent container

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

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);
<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>

我基于 Tim Down 编写了我自己的函数,它可以像您想要的那样工作。我将 treeWalker 更改为过滤 NodeFilter.ELEMENT_NODE 而不是 NodeFilter.SHOW_TEXT,现在 <img/> 元素也在我们的循环中得到处理。我首先存储 range.startOffset,然后递归遍历所有选择树节点。如果它找到一个 img 节点,那么它只将 1 添加到该位置;如果当前节点元素与我们的 range.startContainer 不同,则它会添加该节点的长度。该位置由在每个循环中添加到 charCount 的不同变量 lastNodeLength 更改。最后,当它存在循环并且我们有正确的最终插入符号位置时,它将 lastNodeLength 中剩余的任何内容添加到 charCount,包括图像元素。

最终工作代码 (最后是 returns 14,完全符合您的要求)

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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" id="text">minubyv<img contenteditable="true" src="https://themeforest.net/images/smileys/happy.png" class="emojiText" />iubyvt</div>