如何标记与文本混合的单词

How to tag words mixed with text

我想在发帖时标记一些词,例如 Facebook,并标记一些人,混合文本,使用 jQuery。

这是例子:

请看我的 Plunk 我相信这就是您想要的! 我在 script.js 文件的顶部添加了一个包含 3 个名称的数组("Dave Smith"、"Test User"、"Jim Dot")。实际上,您会从数据库中查询并获取前 100 个左右的元素,在 Facebook 示例中,我会说根据总交互量获取前 200 个好友名称。

我的代码适用于 Google Chrome 版本 40.0.2214.115(我还没有测试过其他浏览器):

重要的代码是 div contenteditable 属性设置为 true:

<div id="tag-area" class="tag-area" contenteditable="true">
</div>

重要的 JavaScript 是用于搜索我的名称数组并将文本包装在 "span" 元素中的代码:

function ExistsInListOfNamesAndIsNotHiglighted(item) {
   return $("#tag-area").html().indexOf(item) > -1 && $("#tag-area").html().indexOf("<span>" + item + "</span>") === -1;
}

$(function() {
  var tags = ["Dave Smith", "Test User", "Jim Dot"];

  $("#tag-area").keyup(function() {
    $(tags).each(function(index, item) {
      if (ExistsInListOfNamesAndIsNotHiglighted(item)) {
        $("#tag-area").html($("#tag-area").html().replace(item, "<span>" + item + "</span>&nbsp;"));

        cursorToEndOfContentEditable($("#tag-area")[0]);
  }
});

"cursorToEndOfContentEditable" 代码取自 Nico Burn 在线程

上的回答

How to move cursor to end of contenteditable entity

我还在 span 标签中添加了一点 CSS,它将包裹标记的文本片段:

span {
  background-color: #D8DFEA; 
  border:1px solid #7688a4;
}

请告诉我你过得怎么样! 并且不要犹豫向我询问任何改进:)

您可以在 jquery 中使用 "Mix text tags" 选项。请参考 https://yaireo.github.io/tagify/