select&多選框
因爲工做須要,在一個原生js項目中,要用到一個selelct&checkbox的組件,在網上屢次搜索無果,故本身寫了個簡陋的。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<style>
#mulBox {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#mulBox ul, li {
list-style: none;
position: relative;
}
#mulCheck, #mulItems {
width: 320px;
border: 1px solid #ccc;
}
#mulCheck {
height: 32px;
position: relative;
cursor: pointer;
}
#mulCheck:after {
content: '';
width: 0;
height: 0;
border: 6px solid transparent;
border-top: 6px solid #5a5a5a;
position: absolute;
right: 6px;
bottom: 6px;
}
#mulItems {
padding: 0;
margin: 0;
display: none;
}
#mulItems input[type=checkbox] {
visibility: hidden;
}
[id^="color-input-blue"] + label {
display: block;
width: 14px;
height: 14px;
cursor: pointer;
position: absolute;
top: 4px;
left: 4px;
/*background: #d0cbd2;*/
background: #1f8bec;
}
[id^="color-input-blue"]:checked + label::before {
display: block;
content: "\2714";
text-align: center;
font-size: 12px;
/*color: #000000;*/
color: #fff;
}
</style>
<div id="mulBox">
<div id="mulCheck"></div>
<ul id="mulItems">
<li>
<input id="color-input-blue1" type="checkbox" value="test11"/>
<label for="color-input-blue1"></label>test11
</li>
<li>
<input id="color-input-blue2" type="checkbox" value="test11test11test11test11"/>
<label for="color-input-blue2"></label>test11test11test11test11
</li>
</ul>
</div>
<script>
var flagK = false;
document.querySelector('#mulCheck').onclick = function () {
toggleUl(!flagK);
}
function toggleUl(oFlag) {
flagK = oFlag;
document.querySelector('#mulItems').style.display = oFlag ? "block" : "none";
var mulRes = getMulItemsValue();
console.log(mulRes);
}
function getMulItemsValue() {
var elArr = document.querySelectorAll("*[id^=color-input-blue]");
var oArr = [];
elArr.forEach((item) => {
if(item.checked) {
oArr.push(item.value)
}
});
return oArr;
}
</script>
</body>
</html>