javascript - DIV 内容可编辑链接格式 : How to prevent the append when typing at the time of input?

标签 javascript jquery html

我正在匹配 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.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/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/

相关文章:

javascript - Slick.js - 响应式断点自定义函数

javascript - 带有 git 样式子命令的 npm 链接

jquery - 重新格式化 JSON 对象

javascript - 今日特辑 : How is this done? 有没有jquery插件或者产品可以做到?

html - 填充未正确应用于 div 元素

javascript - iScroll lite 在我到达滚动末尾或元素底部时找到

javascript - 使用 JavaScript 滚动功能导航到适当的部分

Javascript 数组和 JQuery .param

html - 如何在自定义元素中制作自定义表格?

javascript - 使用哪个选择器?