ContentEditable div-在更新内部html之后设置光标位置

F.S*_*.S. 14 html javascript dom contenteditable cursor-position

我有一个拼写检查解决方案,该解决方案使用可编辑的内容,divspan在拼写错误的单词周围插入标签。每次div更新的内部html时,光标就会移动到的开头div

我知道,div如果用户将新单词添加到句子的末尾(下面的代码),我可以将光标移到末尾。

旧文本:这是拼写检查器|

新文本:这是拼写检查器解决方案|

var range = document.createRange();
range.selectNodeContents(element[0]);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
Run Code Online (Sandbox Code Playgroud)

但是,如果用户在句子中间添加单词,则无法保留光标位置。

旧文本:这是一个拼写检查器

新文本:这是一个新的拼写检查器|

在上述情况下,光标应移至div“ new”之后的末尾。

如何保持光标位置?由于我正在更新html并添加节点,因此无法在更新之前保存范围并将其添加到选择对象中。

提前致谢。

Siv*_*iva 5

据我所知,更改div的内容始终会遇到问题。

所以这是我附带的解决方案。请输入错误字词,例如hello,dudeee

理想情况下,这也应该适用于textarea。

解决方案详细信息:

  • 使用具有相同文本内容的ghost div
  • 对幽灵div使用透明的颜色
  • 使用border-bottom作为ghost div跨度文本
  • 更改zIndex使其不出现在前面

// some mock logic to identify spelling error
const errorWords = ["helloo", "dudeee"];

// Find words from string like '   Helloo   world .. '
// Perhaps you could find a better library you that does this logic.
const getWords = (data) =>{
  console.log("Input: ", data);
  const allWords = data.split(/\b/);
  console.log("Output: ", allWords)
  return allWords;
}

// Simple mock logic to identify errors. Now works only for 
// two words [ 'helloo', 'dudeee']
const containsSpellingError = word => {
  const found = errorWords.indexOf(word) !== -1;
  console.log("spell check:", word, found);
  return found;
}

const processSpellCheck = text => {
  const allWords = getWords(text);
  console.log("Words in the string: ", allWords);
  const newContent = allWords.map((word, index) => {
    var text = word;
    if(containsSpellingError(word.toLowerCase())) {
      console.log("Error word found", word);
      text = $("<span />")
        .addClass("spell-error")
        .text(word);
    }
    return text;
  });
  return newContent;
}

function initalizeSpellcheck(editorRef) {
  var editorSize = editorRef.getBoundingClientRect();
  
  var spellcheckContainer = $("<div />", {})
    .addClass("spell-check")
    .prop("spellcheck", "false");
 
  var spellcheckSpan = $("<span />")
    .addClass("spell-check-text-content")
    .css({
      width: editorSize.width,
      height: editorSize.height,
      position: "absolute",
      zIndex: -1
    });
    
  var text = $(editorRef).text();
  
  var newContent = processSpellCheck(text);
  spellcheckSpan.append(newContent);
  
  spellcheckContainer.append(spellcheckSpan);
  spellcheckContainer.insertBefore(editorRef);
  
  $(editorRef).on("input.spellcheck", function(event) {
      var newText = $(event.target).text();
      var newContent = processSpellCheck(newText); 
      $(".spell-check .spell-check-text-content").text("");
      $(".spell-check .spell-check-text-content").append(newContent);
  });
}


$(document).ready(function() {
  var editor = document.querySelector("#editor");
  initalizeSpellcheck(editor);
});
Run Code Online (Sandbox Code Playgroud)
#editor {
  border: 1px solid black;
  height: 200px;
}

.spell-check {
  color: transparent;
}

.spell-error {
  border-bottom: 3px solid orange;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="editor" contenteditable="true" spellcheck="false">
dudeee
</div>
Run Code Online (Sandbox Code Playgroud)


And*_*rew 0

这个答案可能适用于 SitePoint:

存储选择 x, y:

cursorPos=document.selection.createRange().duplicate();
clickx = cursorPos.getBoundingClientRect().left;
clicky = cursorPos.getBoundingClientRect().top;
Run Code Online (Sandbox Code Playgroud)

恢复选择:

cursorPos = document.body.createTextRange();
cursorPos.moveToPoint(clickx, clicky);
cursorPos.select();
Run Code Online (Sandbox Code Playgroud)

SitePoint 文章:在 contentEditable div 中保存/恢复插入符位置

2019 年 10 月 25 日更新:

上面提到的解决方案不再有效,因为使用了已弃用的函数。chrome 支持 document.selection 吗?