如何制作标签文本框

时间:2012-11-14 17:06:51

标签: javascript jquery jquery-ui knockout.js

在stackoverflow中,当我们发帖子时,我们可以看到一个文本框“标签”。

在输入单词和空格时,它会变成标签。在成为标签之后,我们从一个单词中删除一个字母。但是我们可以通过单击X图像来删除单词本身。

我想为标签创建一个类似的文本框。 在stackoverflow中有自动建议也与此文本框相关联,但我不需要它。

欢迎任何帮助/链接

2 个答案:

答案 0 :(得分:8)

这些网上有很多这样的东西。我发现有些人很容易使用Google。例如,看看这个:

http://xoxco.com/projects/code/tagsinput/

答案 1 :(得分:6)

编辑: 以下是一个类似的示例,其功能略有不同(更好):
https://stackoverflow.com/a/14083331/383904


一个很好的小型演示,您可以轻松升级和修改:

$('#tags input').on('focusout',function(){    
  var txt = $.trim( this.value );
  if(txt) {
    $(this).before('<span class="tag">'+txt+'</span>');
  }
  this.value = "";  
});


$('#tags').on('click','.tag',function(){
  if( confirm("Really delete this tag?") ) $(this).remove();
});
#tags{
  float:left;
  border:1px solid #ccc;
  padding:5px;
  font-family:Arial;
}
#tags span.tag{
  display:block;
  float:left;
  color:#fff;
  background:#689;
  padding:5px;
  padding-right:25px;
  margin:4px;
}
#tags span.tag:after{
  position:absolute;
  content:"x";
  border:1px solid;
  padding:0 4px;
  margin:3px 0 10px 5px;
  cursor:pointer;
  font-size:10px;
}
#tags input{
  background:#eee;
  border:0;
  margin:4px;
  padding:7px;
  width:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tags">
  <input type="text" value="" placeholder="Add a tag" />
</div>