<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>原生js实现多选功能</title>
</head>
<body>
<div>
<label>多选功能:</label>
<select id="multipleSelect" onchange="getValue('multipleSelect')">
<option selected="selected" disabled="disabled" style='display: none' data-value=''></option>
<option>HTML</option>
<option>CSS</option>
<option>Javascript</option>
<option>vue</option>
<option>react</option>
</select>
</div>
<script>
/*基本思路:
1、创建一个隐藏的option,添加到select的最后;
2、每次选中的值都存入这个option,如果已经选中,当再次选择时,就会删掉;
3、若已选择了值,就将隐藏的option的selected属性设置为true,以便获取多选内容
*/
function getValue(id) {
const event = window.event
const multipleSelect = document.getElementById(id)
const optionList = document.querySelectorAll(`#${id} option`)
const innerHtmlarr = []
for (let i = 0; i < optionList.length; i++) {
innerHtmlarr.push(optionList[i].innerHTML)
}
if (optionList[0].getAttribute('data-value') == '') {
optionList[0].setAttribute('data-value', event.target.value)
optionList[innerHtmlarr.indexOf(event.target.value)].style = 'background:red'
} else {
const list = optionList[0].getAttribute('data-value').split(',')
if (list.indexOf(event.target.value) > -1) {
list.splice(list.indexOf(event.target.value), 1)
optionList[0].setAttribute('data-value', list.join(','))
optionList[innerHtmlarr.indexOf(event.target.value)].style = 'background:#fff'
} else {
list.push(event.target.value)
optionList[0].setAttribute('data-value', list.join(','))
optionList[innerHtmlarr.indexOf(event.target.value)].style = 'background:red'
}
if (list.length >= 1) {
event.target.value = optionList[0].innerHTML
optionList[0].innerHTML = list.join(',')
} else {
optionList[0].setAttribute('data-value', '')
optionList[0].innerHTML = ''
event.target.value = null
for (let i = 0; i < optionList.length; i++) {
optionList[i].style = 'background:#fff;'
}
optionList[0].setAttribute('selected', 'selected')
optionList[0].style = 'display:none'
}
}
//打印当前选中的值
console.log("🚀 ~ file: 新建 文本文档 (4).html:53 ~ getValue ~ event.target.value:", event.target.value)
}
</script>
</body>
</html>
实现原理: