带有动态链接标记的可满足元素(JS、jQuery)

contenteditable elements with markup for links on the fly (JS, jQuery)

本文关键字:元素 JS jQuery 可满足 动态 链接      更新时间:2023-09-26

我正在构建一个精益& &;干净的html/js文本编辑器,类似于Medium的写作工具。我使用contenteditable来使div可编辑。

我想为文本链接添加内联标记(例如输入[[Google|https://www.google.com]]立即转换为<a href='https:www.google.com'>Google</a>,即Google)。所有这些都应该在飞行中发生,即在打字时。也就是说,当用户键入链接标记的第二个关闭]或者光标焦点设置在[[text|url]]元素之外时,JS识别出该事件并立即将[[text|url]]转换为html链接。另一方面,如果焦点设置在现有的文本链接上(即,在可编辑div的<a>...</a> html标签内),(1)链接的默认打开行为被阻止,(2)文本链接立即转换回标记版本进行编辑(例如,Google变成[[Google|https://www.google.com]])。

我不太熟悉JS中的regex。知道怎么做吗?

非常感谢你的帮助。PS:我使用jQuery 1.11.0

PSS:期望的行为有点类似于本文本编辑器在退格到链接时的行为(删除]将链接转换为标记版本,输入结束的]将标记版本转换为链接)。不同之处在于,我没有将书写字段与显示的文本分开,所有内容都是内联的。

看看这个小提琴

这只是一个样品。

它将[[Google|https://www.google.com]]转换为<a href='https://www.google.com'>Google</a>,即Google。

我使用这个正则表达式来检测内联标记。

它有一些bug,但是我认为它会帮助你实现你所需要的。

下面是代码片段。

$('.editor').keyup(function(e) {
  if (e.keyCode === 221) {
    var text = $('.editor').html();
    var match = /'['[(.+)'|(https?:'/'/.*'..+)']']/g.exec(text);
    if (match !== null) {
      text = text.replace(match[0], "<span><a href='" + match[2] + "'>" + match[1] + "</a></span>");
      $('.editor').html(text);
    }
  }
});
.editor {
  position: absolute;
  border: black dashed 2px;
  left: 5%;
  right: 5%;
  top: 10%;
  bottom: 10%;
  padding: 15px;
  font-family: 'Lucida Console';
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="editor" contenteditable='true'>This is the Editor. write something here.</div>