今天借用几分钟,写了一个回车添加标签、删除标签、标签获取的js,大家可以随意使用啊!!!
html:
<div id="">
<div id="tagsContainer">
<input type="text" id="tagIn" size="8" maxlength="15" placeholder="输入标签回车"/>
</div>
</div>
css:
<style type="text/css">
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
#tagsContainer{
display: flex;
width: 800px;
height: 34px;
border: 1px solid crimson;
border-radius: 5px;
margin: 16px;
align-items: center;
}
.tags{
background-color: #DC143C;
color: white;
font-size: 16px;
padding: 0px 10px;
display: block;
height: 22px;
margin-left: 8px;
border-radius: 5px;
cursor: pointer;
}
.tags:hover .remove-tag::before{
content: "X";
}
.remove-tag::before{
padding: 0px 5px;
width: 14px;
height: 14px;
font-size: 13px;
margin-left: 3px;
background-color: #dc545d;
border-radius: 100%;
cursor: pointer;
}
#tagIn{
outline: none;
border: none;
padding: 0px 8px;
margin-left: 5px;
background: transparent;
color: #4a4a4a;
}
</style>
js:
(function(){
// 移除标签
function tagFC(){
var removeHandle=document.querySelectorAll(".remove-tag");
removeHandle.forEach((ele)=>{
ele.addEventListener("click",()=>{
ele.parentElement.remove();
})
})
}
// 回车创建标签
var tagIn=document.querySelector("#tagIn");
var tagsContainer=document.querySelector("#tagsContainer");
document.onkeypress=function enterDoLongin(){
if(tagIn.value){
if(event.keyCode==13){
var newTag=document.createElement("span");
newTag.className="tags";
newTag.innerHTML=`${tagIn.value}<span class="remove-tag"></span>`;
// 把标签添加进去
tagsContainer.insertBefore(newTag,tagIn);
tagIn.value="";
tagFC();
getTags();
}
}
}
// 收集标签
var tags=[];
function getTags(){
var removeHandle=document.querySelectorAll(".tags");
tags=[];
removeHandle.forEach((ele)=>{
tags.push(ele.innerText);
});
console.log(tags);
}
}).call()