【问题标题】:How to tag words mixed with text如何标记与文本混合的单词
【发布时间】:2015-03-02 21:19:58
【问题描述】:

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

这是一个例子:

【问题讨论】:

  • 我认为需要更好的描述
  • 如何制作和图片一样的?有些词被标记了另一些则没有。

标签: javascript jquery tags


【解决方案1】:

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

我的代码适用于 Google Chrome 版本 40.0.2214.115(我尚未测试其他浏览器):

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

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

请告诉我你的进展如何! 如果有任何改进,请随时向我询问:)

【讨论】:

    【解决方案2】:

    您可以在 jquery 中使用“混合文本标签”选项。请参考 https://yaireo.github.io/tagify/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2021-11-08
      • 2015-12-06
      • 1970-01-01
      相关资源
      最近更新 更多