1 回答
TA贡献1812条经验 获得超5个赞
您的选择器错误,您使用的div是类.input而不是实际input元素。
$此外,如果值将成为 jQuery 元素,则应在变量(按照惯例)前加上 a 前缀。这将减少后面代码中的混乱。
jQuery(document).ready(function($) {
let $input = $("#input");
setTimeout(function() {
$input.html($input.html() + "and I'm <b>very bold</b>");
placeCaretAtEnd($input[0]);
}, 1000);
});
/**
* @param {Element} el - A Native DOM Element
*/
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>
非 jQuery 方法非常相似且简单。
window.addEventListener('DOMContentLoaded', () => {
let input = document.querySelector("#input");
setTimeout(function() {
input.innerHTML += "and I'm <b>very bold</b>";
placeCaretAtEnd(input);
}, 1000);
});
/**
* @param {Element} el - A Native DOM Element
*/
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;
}
<div id="input" contenteditable="true" spellcheck="true">I'm a <span>text</span> </div>
添加回答
举报