用jQuery替换HTML后,如何将光标置于文本的末尾? [英] How to place cursor at the end of text after replacing HTML with jQuery?
问题描述
我有一个内容可编辑的div,试图用<span>
标签替换<font>
标签,但是在使用jQuery replaceWith()
函数替换html之后,光标默认为文本的开头,但是我希望在替换结束时使用它html.
I have a contenteditable div and trying to replace <font>
tag with <span>
tag but after replacing the html using jQuery replaceWith()
function cursor defaults to the beginning of the text however I want it at the end of the replacing html.
以下是演示,以重现此问题.让我知道重现问题是否存在.
Here is the DEMO to reproduce the issue. Let me know if there is any problem reproducing the issue.
这是演示代码要点
<div id="test" contenteditable=true>
<p> <font color="blue">Text to be replaced</font> </p>
</div>
<a id="replace" href="javascript:void(null);">replace</a>
JS代码
$('#test').focus();
$('#replace').on({
mousedown: function (event) {
event.preventDefault();
},
click: function () {
$('#test').find('font').replaceWith(function () {
return '<span style="color:red">' + 'New Text' + '</span>'
});
}
});
在这里听起来可能是重复的问题,但是当您看到内容被替换时确实不同.我可能要替换用户选择的部分文本,而不是整个文本.因此,我需要将光标放在要替换原始html的html的末尾.
Here the problem may sound duplicate but it is indeed different as you see the content gets replaced. I might be replacing the part of that text selected by user and not the entire text. So I need to place the cursor at the end of the html which is replacing the original html.
推荐答案
您可以使用此功能
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();
}
}
称呼它
placeCaretAtEnd( document.getElementById("content") );
这篇关于用jQuery替换HTML后,如何将光标置于文本的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!