作者:小菜鸟 | 来源:互联网 | 2023-02-06 08:33
我有一个拼写检查解决方案,该解决方案使用可编辑的内容,div
并span
在拼写错误的单词周围插入标签。每次div
更新的内部html时,光标就会移动到的开头div
。
我知道,div
如果用户将新单词添加到句子的末尾(下面的代码),我可以将光标移到末尾。
旧文本:这是拼写检查器|
新文本:这是拼写检查器解决方案|
var range = document.createRange();
range.selectNodeContents(element[0]);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
但是,如果用户在句子中间添加单词,则无法保留光标位置。
旧文本:这是一个拼写检查器
新文本:这是一个新的拼写检查器|
在上述情况下,光标应移至div
“ new”之后的末尾。
如何保持光标位置?由于我正在更新html并添加节点,因此无法在更新之前保存范围并将其添加到选择对象中。
提前致谢。
1> Siva..:
据我所知,更改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 = $("")
.addClass("spell-error")
.text(word);
}
return text;
});
return newContent;
}
function initalizeSpellcheck(editorRef) {
var editorSize = editorRef.getBoundingClientRect();
var spellcheckCOntainer= $("", {})
.addClass("spell-check")
.prop("spellcheck", "false");
var spellcheckSpan = $("")
.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);
});
#editor {
border: 1px solid black;
height: 200px;
}
.spell-check {
color: transparent;
}
.spell-error {
border-bottom: 3px solid orange;
}
dudeee