【问题标题】:DIV contentEditable Link formatting: How to prevent the append when typing at the time of input?DIV contentEditable 链接格式:输入时如何防止追加?
【发布时间】:2016-11-26 10:15:57
【问题描述】:

我是匹配 url 链接并使用一些正则表达式将 a 标记替换为可点击的链接类型。它的工作完美。匹配的文本应用到输入后。文本将输入错误的位置。所有文本也将附加.

参见下面的 sn-p

请在 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>

【问题讨论】:

  • 您可以查看以下答案

标签: javascript jquery html


【解决方案1】:

当您替换文本时,您必须使用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>

【讨论】:

  • 哇。太棒了。非常感谢
猜你喜欢
  • 1970-01-01
  • 2011-05-02
  • 2013-09-04
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多