我正在匹配 url 链接并使用一些正则表达式将 a
标记替换为可点击的链接类型。它的工作完美。在匹配的文本应用于输入后。文本将在错误的位置输入。而且将附加所有文本。
请参阅以下代码片段:
请在要附加的 div 内输入内容。请帮助如何防止附加和光标始终位于文本末尾。
function testinf(that){
var some="";
some =that.innerHTML.replace(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/g, function(match){
return '<a href="'+match+'" target="_blank">'+match+'</a>';
});
that.innerHTML=that.innerHTML;
that.innerHTML=some;
console.log(some)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div oninput="testinf(this)" contentEditable="true">sone http://www.some.com type</div>
最佳答案
替换文本时,必须使用如下的 textContent
而不是 innerHTML
。另外,我在下面给出了一个跨浏览器的方法来将光标移动到末尾。
function testinf(that){
var some = "";
some = that.textContent.replace(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/g, function(match){
return '<a href="'+match+'" target="_blank">'+match+'</a>';
});
//that.innerHTML=that.innerHTML;
that.innerHTML = some;
placeCaretAtEnd(that);
console.log(some)
}
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();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div oninput="testinf(this)" contentEditable="true">sone http://www.some.com type</div>
关于javascript - DIV 内容可编辑链接格式 : How to prevent the append when typing at the time of input?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40817238/