先来看看效果
html
<div class="select">
<div class="label">
标签多选框:
</div>
<div class="multiSelected">
<div class="value"><span>选择</span></div>
<div class="list">
<ul>
<li>选项1</li>
<li>选项2</li>
<li>选项3</li>
</ul>
</div>
</div>
</div>
<button>获取值</button>
css
.select {
width: 500px;
display: flex;
align-items: center;
justify-content: space-between;
}
.multiSelected {
width: 400px;
height: 32px;
position: relative;
display: flex;
align-items: center;
justify-content: space-between;
}
.value {
width: 400px;
height: 32px;
border: 1px solid #D9D9D9;
border-radius: 2px;
line-height: 32px;
padding-left: 12px;
box-sizing: border-box;
position: relative;
font-family: PingFang SC;
font-style: normal;
font-weight: normal;
font-size: 14px;
line-height: 30px;
color: #BDBDBD;
display: flex;
align-items: center;
}
.value > span:first-child {
position: absolute;
z-index: 0;
}
/*下拉框图标*/
.value:after {
content: '';
position: absolute;
width: 12px;
height: 12px;
right: 12px;
top: 50%;
transform: translateY(-50%);
background: url("icon.svg") no-repeat center;
}
.list {
width: 400px;
border-radius: 2px;
position: absolute;
border: 1px solid #D9D9D9;
background: #fff;
right: 0;
top: 34px;
box-sizing: border-box;
display: none;
}
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
width: 100%;
height: 32px;
line-height: 32px;
box-sizing: border-box;
padding-left: 12px;
cursor: pointer;
}
ul li:hover {
background: #f3f3f3;
}
.choose {
background: #f3f3f3;
color: #57a3f3;
}
.lb {
font-size: 12px;
display: inline-block;
height: 24px;
line-height: 24px;
color: rgba(0, 0, 0, 0.65);
background: #F5F5F5;
border: 1px solid #F0F0F0;
box-sizing: border-box;
border-radius: 2px;
padding: 0 10px;
margin-right: 4px;
pointer-events: none; /*设置只点击x才触发事件*/
z-index: 5;
}
.lb:after {
content: 'x';
width: 10px;
height: 10px;
margin-left: 4px;
pointer-events: auto
}
js
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
// 点击显示或隐藏选项
$('.value').on('click', function () {
$('.list').toggle();
});
//点击选项生成标签
$('ul').on('click', 'li', function () {
if (!$(this).hasClass('choose')) {
$(this).addClass('choose');
let val = $(this).text();
let span = `<span class="lb">${val}</span>`;
$('.value').append(span);
}
});
// 点击x删除标签
$('.value').on('click', '.lb', function (e) {
e.stopPropagation();
let val = $(this).text();
$(this).parent().next().find(`li:contains(${val})`).removeClass('choose');
$(this).remove();
});
//点击空白处隐藏选项
$(document).click(function(event){
const _con = $(".multiSelected"); // 设置点击失效目标区域
if(!_con.is(event.target) && _con.has(event.target).length === 0){
$(".multiSelected .list").hide()
}
});
//获取选择的值
$('button').on('click', function () {
let choosed = []
let data = $('.value').children().not(':first');
for (let i of data) {
choosed.push($(i).text());
}
alert(choosed)
});
</script>