在插入之后将插入符号设置为满足于contenteditable div

时间:2017-08-22 15:03:49

标签: javascript jquery html

我正在使用ATD插件进行拼写检查,但我希望光标移动到ATD添加的可编辑div的末尾。

function placeCaretAtEnd(el) {
  el.focus();
  if (typeof window.getSelection != "undefined" &&
    typeof document.createRange != "undefined") {
    var range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (typeof document.body.createTextRange != "undefined") {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.collapse(false);
    textRange.select();
  }
}
<div id="recap_area" style="height: 54px; overflow: auto; white-space: pre-wrap; outline: none; background-color: rgb(255, 255, 255); color: rgb(85, 85, 85); font-size: 14px; font-family: &quot;Open Sans&quot;, sans-serif; border-width: 1px; border-style: solid; border-color: rgb(0, 0, 0); text-align: start; margin: 0px; width: 1263px; line-height: 20px; letter-spacing: 0px; left: auto; right: auto; top: auto; bottom: auto; position: static; padding: 6px 12px;"
  class="form-control required valid" contenteditable="true" spellcheck="false"><span class="mceItemHidden"> <span class="hiddenSpellError" pre="">sasa</span> running </span>
</div>

问题是div包含span s,所以我无法将光标移动到最后。

1 个答案:

答案 0 :(得分:1)

您的代码运行正常。我添加了一个按钮,表明它会将光标放在最后。

function placeCaretAtEnd(el) {
  el.focus();
  if (typeof window.getSelection != "undefined" &&
    typeof document.createRange != "undefined") {
    var range = document.createRange();
    range.selectNodeContents(el);
    range.collapse(false);
    var sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (typeof document.body.createTextRange != "undefined") {
    var textRange = document.body.createTextRange();
    textRange.moveToElementText(el);
    textRange.collapse(false);
    textRange.select();
  }
}

var recap_area = document.querySelector('#recap_area');
var button = document.querySelector('button');

button.onclick = function() {
  placeCaretAtEnd(recap_area);
}
.hiddenSpellError { color: red }
<div id="recap_area" style="height: 54px; overflow: auto; white-space: pre-wrap; outline: none; background-color: rgb(255, 255, 255); color: rgb(85, 85, 85); font-size: 14px; font-family: &quot;Open Sans&quot;, sans-serif; border-width: 1px; border-style: solid; border-color: rgb(0, 0, 0); text-align: start; margin: 0px; width: 1263px; line-height: 20px; letter-spacing: 0px; left: auto; right: auto; top: auto; bottom: auto; position: static; padding: 6px 12px;"
  class="form-control required valid" contenteditable="true" spellcheck="false"><span class="mceItemHidden"> <span class="hiddenSpellError" pre="">sasa</span> running </span>
</div>

<button>Place cursor at end</button>