使用CSS的flex属性,让标签自动换行。
代码示例:
HTML部分:
CSS部分:
.tag-container {
display: flex;
flex-wrap: wrap;
align-items: center;
border: 1px solid #ccc;
padding: 10px;
}
.tags {
display: flex;
flex-wrap: wrap;
margin-left: 10px;
}
.tag {
background-color: #ccc;
color: #fff;
padding: 5px;
margin: 2px;
}
JavaScript部分:
const input = document.querySelector('input');
const tags = document.querySelector('.tags');
let selectedTags = [];
input.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
event.preventDefault();
const tag = event.target.value.trim();
if (tag !== '' && !selectedTags.includes(tag)) {
selectedTags.push(tag);
const tagElement = document.createElement('span');
tagElement.classList.add('tag');
tagElement.textContent = tag;
tags.appendChild(tagElement);
event.target.value = '';
}
}
});
tags.addEventListener('click', (event) => {
if (event.target.classList.contains('tag')) {
const tag = event.target.textContent;
selectedTags = selectedTags.filter(t => t !== tag);
event.target.remove();
}
});