contenteditable 中的自动链接 URL

2022-01-24 00:00:00 selection range javascript

当用户完成在 contenteditable div 中输入 URL 时,我想自动链接它,就像 Medium 一样:).

When the user finishes to type in a URL in a contenteditable div, I want to autolink it, like Medium does: ).

我想知道如何使用选择/范围来实现这一点(我不需要支持 IE,只支持 Chrome、Firefox 和 Safari 的现代版本),如果可能的话没有范围(但如果这是唯一的解决方案我会用它).

I'm wondering how it is possible to achieve that using selection/range (I do not need to support IE, only modern versions of Chrome, Firefox and Safari), if possible without rangy (but if that is the only solution I would use it).

在用户按下空格键后,我能够检测 URL 是否在插入符号之前,但我不能让 execcommand('createLink'...) 在我的范围内工作.

I'm able to detect if an URL preceed the caret after a user presses the space key, but I can't have execcommand('createLink'...) work on my range.

这是一个非常简化的示例(jsfiddle),我尝试将其格式化为粗体用户按下空格键后插入符号前的 4 个字符:

Here is a very simplified example (jsfiddle) where I try to format in bold the 4 characters preceding the caret after the user presses the space key:

$("#editor").on("keypress", function(event) {
  var pressedChar = String.fromCharCode(event.which);
  if(/s/.test(pressedChar)) {
    var selection   = window.getSelection();
    var range       = selection.getRangeAt(0);
    range.setStart(range.startContainer, range.startOffset - 4);

    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand('bold', false);
  }
}

当我输入几个字符,然后输入一个空格时,前面的 4 个字符没有按照我的意愿设置为粗体,它们只是从 div 中消失,只有我之后键入的新字符是粗体.

When I type a few characters and then a space, the 4 previous characters are not formatted in bold as I'd like, they just disappear from the div and only the new characters that I type afterwards are bolded.

推荐答案

终于找到了解决方法,不用execCommand:

Finally found a workaround, without using execCommand:

  1. 删除范围内容:range.deleteContents()
  2. 创建我要插入的链接节点
  3. 在范围内插入节点:range.insertNode(createdLinkNode)
  4. 在插入的节点之后放置插入符号:

 

range.setStartAfter(createdLinkNode);
range.setEndAfter(createdLinkNode);
selection.removeAllRanges();
selection.addRange(range);

相关文章