如何制作一个“标签盒”使用jQuery(文本输入字段+用逗号分隔的标签) [英] How to make a "tags box" using jQuery (with text input field + tags separated by comma)

查看:119
本文介绍了如何制作一个“标签盒”使用jQuery(文本输入字段+用逗号分隔的标签)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个允许用户按标签发布内容的网络应用程序,但问题是,如果用逗号和文本字段分隔,我将如何在标记周围创建一个很好的块?值仍然是相同的只有用户的视图会有所不同。

I am working on a web application that allows users to post content by tags but the thing is, how would I make a nice block around a tag if its separated by a comma and the text field value would still be the same only the view to the user would differ.

例如YouTube或StackOverflow,现在我不需要它来检查数据库或任何东西。

An example would be such as YouTube or StackOverflow, for now I don't need it to check a database or anything.

谢谢!

推荐答案

类似Stack Overflow的东西:

Something similar like Stack Overflow does:


  • 允许字母数字和 + - 。#(并修剪空格!)

  • 转换为小写

  • 自动创建 focusOut上的标签框 输入 (添加更多 | 分隔的keyCodes)

  • 点击时删除标签框(带确认)

  • Allows alphanumeric and +-.# (and trims whitespaces!)
  • Convert to lowercase
  • Create automatically the Tag Box on focusOut Enter , (add more | delimited keyCodes)
  • Delete Tag Box on click (with confirmation)

$(function(){ // DOM ready

  // ::: TAGS BOX

  $("#tags input").on({
    focusout : function() {
      var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
      if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
      this.value = "";
    },
    keyup : function(ev) {
      // if: comma|enter (delimit more keyCodes with | pipe)
      if(/(188|13)/.test(ev.which)) $(this).focusout(); 
    }
  });
  $('#tags').on('click', 'span', function() {
    if(confirm("Remove "+ $(this).text() +"?")) $(this).remove(); 
  });

});

#tags{
  float:left;
  border:1px solid #ccc;
  padding:5px;
  font-family:Arial;
}
#tags > span{
  cursor:pointer;
  display:block;
  float:left;
  color:#fff;
  background:#789;
  padding:5px;
  padding-right:25px;
  margin:4px;
}
#tags > span:hover{
  opacity:0.7;
}
#tags > span:after{
 position:absolute;
 content:"×";
 border:1px solid;
 padding:2px 5px;
 margin-left:3px;
 font-size:11px;
}
#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">
  <span>php</span>
  <span>c++</span>
  <span>jquery</span>
  <input type="text" value="" placeholder="Add a tag" />
</div>

这篇关于如何制作一个“标签盒”使用jQuery(文本输入字段+用逗号分隔的标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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