Autolink URL in contenteditable

痞子三分冷 提交于 2019-11-30 16:18:54

问题


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

).

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).

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.

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);
  }
}

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.


回答1:


Finally found a workaround, without using execCommand:

  1. delete the range content: range.deleteContents()
  2. create the link node I want to insert
  3. insert the node in the range: range.insertNode(createdLinkNode)
  4. place the caret right after the inserted node:

 

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


来源:https://stackoverflow.com/questions/20127418/autolink-url-in-contenteditable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!