如何从具有HTML元素作为文本的Content Editable Div中获取光标位置

时间:2019-02-16 11:30:40

标签: jquery contenteditable cursor-position

我有以下代码,其中DIVContenteditable。并且,div也包含不可编辑的文本。

现在,当我尝试获取光标位置时,当光标位于任何Non Editable Text上时,该位置将重置为0。有什么想法吗?

var currentCaretPosition;

var update = function() {

  currentCaretPosition = getCaretPosition(this);

  console.log("Current Position: " + currentCaretPosition);
}
$('#test').on("mousedown mouseup keydown keyup", update);


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;
            }
.text-editor {
  border: solid 1px gray;
  border-radius: 5px;
  min-height: 100px;
  margin: 5px 0;
  padding: 2px;
}

span[contenteditable="false"] {
  border: solid 1px red;
}

p
{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="col-lg-12">
    <div id="test" class="text-editor" contenteditable="true">Normal Text <span contenteditable="false">NotEditableText</span></div>
  </div>
</div>
<p>
Place the cursor in above div and move from start and when it reaches NotEditableText the cursor position is again set to 0
</p>

0 个答案:

没有答案