回车添加删除标签

17 篇文章 0 订阅
8 篇文章 0 订阅

今天借用几分钟,写了一个回车添加标签、删除标签、标签获取的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()

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

圈点Studio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值