在contenteditable中自动链接URL [英] Autolink URL in contenteditable

查看:252
本文介绍了在contenteditable中自动链接URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户完成输入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).

I在用户按下空格键后能够检测到插入符号之前是否有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. 将插入符号放在插入的节点后面:

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

这篇关于在contenteditable中自动链接URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆