我的功能有问题。我的目标是更改我的 contenteditable div 的内容。这很好用,但我让光标跳转开始问题。所以我在 SO 上找到了一个功能来解决这个问题。可悲的是,这个函数不像预期的那样工作并引发错误。也许是因为我在整个项目中都使用了 jQuery?
jQuery(document).ready(function ($) {
let input = $("input");
setTimeout(function () {
input.html(input.html() + "and I'm <b>very bold</b>");
placeCaretAtEnd(input);
}, 1000);
});
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection !== "undefined" && typeof document.createRange !== "undefined") {
let range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange !== "undefined") {
let textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
[contenteditable=true] {
border: 1px solid #aaaaaa;
padding: 8px;
border-radius: 12px;
margin-bottom: 20px;
white-space: pre-wrap;
word-wrap: break-word;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="input" contenteditable="true" spellcheck="true">I'm a <span>text</span> </div>
ABOUTYOU
相关分类