Tag Input Configuration
Preview
HTML
1<div class="tag-input-container">
2 <div class="tags">
3 <span class="tag">React<span class="tag-remove">×</span></span><span class="tag">TypeScript<span class="tag-remove">×</span></span>
4 </div>
5 <input type="text" class="tag-input" placeholder="Add tags...">
6</div>
CSS
1.tag-input-container {
2 background-color: #ffffff;
3 border: 1px solid #cccccc;
4 border-radius: 4px;
5 padding: 5px;
6 display: flex;
7 flex-wrap: wrap;
8 align-items: center;
9}
10
11.tags {
12 display: flex;
13 flex-wrap: wrap;
14 padding: 0;
15 margin: 8px 0 0 0;
16}
17
18.tag {
19 width: auto;
20 height: 32px;
21 display: flex;
22 align-items: center;
23 justify-content: center;
24 color: #333333;
25 padding: 0 8px;
26 font-size: 14px;
27 list-style: none;
28 border-radius: 6px;
29 margin: 0 8px 8px 0;
30 background: #e0e0e0;
31}
32
33.tag-remove {
34 display: block;
35 width: 16px;
36 height: 16px;
37 line-height: 16px;
38 text-align: center;
39 font-size: 14px;
40 margin-left: 8px;
41 color: #333333;
42 border-radius: 50%;
43 background: #fff;
44 cursor: pointer;
45}
46
47.tag-input {
48 flex: 1;
49 border: none;
50 height: 46px;
51 font-size: 14px;
52 padding: 4px 0 0 0;
53 color: #000000;
54 background: #ffffff;
55}
56
57.tag-input:focus {
58 outline: transparent;
59}
JavaScript
1document.addEventListener('DOMContentLoaded', function() {
2 const container = document.querySelector('.tag-input-container');
3 const input = container.querySelector('.tag-input');
4
5 container.addEventListener('click', function() {
6 input.focus();
7 });
8
9 input.addEventListener('keydown', function(e) {
10 if (e.key === 'Enter' && this.value.trim() !== '') {
11 const tag = createTag(this.value.trim());
12 this.value = '';
13 const tags = container.querySelector('.tags');
14 tags.appendChild(tag);
15 }
16 });
17
18 function createTag(label) {
19 const div = document.createElement('div');
20 div.setAttribute('class', 'tag');
21 const span = document.createElement('span');
22 span.innerHTML = label;
23 const closeBtn = document.createElement('span');
24 closeBtn.setAttribute('class', 'tag-remove');
25 closeBtn.innerHTML = '×';
26 closeBtn.addEventListener('click', function() {
27 div.remove();
28 });
29 div.appendChild(span);
30 div.appendChild(closeBtn);
31 return div;
32 }
33});