JSFiddle - React, Tailwind, and code Playground
by Samir Chaves
HTML
<div class="tags">
<input type="text" value="html, css, javascript, php">
</div>
CSS
/* Div que a caixa de texto está inserida */
.tagInsert {
width: auto;
display: block;
}
/*Caixa de texto*/
.newTag {
height: 28px;
min-width: 80px;
border: none;
outline: none;
}
/* Box de cada tag */
.tag {
display: inline-block;
line-height: 20px;
height: auto;
background: #13d277;
border: 2px solid #0e9856;
padding: 3px 5px;
margin: 1px 3px;
border-radius: 5px;
color: #fff;
max-width: 100%;
word-break: break-all;
}
/* Botão de fechar */
.tagClose {
display: inline-block;
margin-left: 7px;
background: #0e9856;
color: #fff;
width: 10px;
height: 10px;
padding: 2px;
border-radius: 100%;
line-height: 110%;
font-size: 7pt;
text-align: center;
cursor: pointer;
font-family: 'Trebuchet MS', sans-serif;
}
/* Alinhando a caixa de texto e as tags */
.tags div {
display: inline-block;
}
/* Div geral */
.tags {
border: 2px solid #666;
border-radius: 5px;
background: #fff;
height: auto;
padding: 5px;
}
JavaScript
function tagCreator(par){
par.append('<div class="tagInsert"></div>');
var newTags = par.children('input:text');
newTags.addClass('newTag');
newTags.appendTo('.tagInsert');
$('.tagInsert').add(newTags);
var tags = $('input:text').val().split(',');
function renderTags(){
tags.forEach(function(el, i) {
if (i != tags.length) {
newTags.before('<div class="tag"><span class="tagName">' + el + '</span><span class="tagClose">x</span></div>');
}
})
$('.newTag').val('');
}
renderTags()
var i = 0;
$('input:text').bind("keyup", function(e) {
$(this).css('max-width', $(this).closest('div').parent('div').width());
$(this).css('width', (this.value.length + 1) * 6);
if ((e.keyCode == 13 || e.keyCode == 188) && this.value != "") {
e.preventDefault();
$('.tag').remove();
tags.push(this.value.replace(',', ''))
renderTags();
}
if (e.keyCode == 8 && this.value == "") {
i++;
if (i == 1) {
$('.tag:last').css('opacity', '0.6');
}else if (i == 2) {
$('.tag:last').remove();
tags.pop();
i = 0;
}
}
})
$(document).on('click', '.tagClose', function(e) {
tags.splice($(this).index('.tagClose'), 1);
$(this).closest('div.tag').remove();
})
}
tagCreator($('.tags'));