使用ul li 实现下拉列表多选
使用ul li 实现下拉列表多选,select为固定样式,但使用ul li 可自定义样式,具体实例如下:
<html>
<body>
<input type="text" id="selectInput" placeholder="请选择">
<!-- <div id="show" sytle="width:200px;height:30px;border:solid 2px black">请选择名称</div> -->
<ul id="optionLis" style="margin-left:20px;width: 100px;height: 120px;border: solid 2px black">
<li style="list-style-type:none;">万达</li>
<li style="list-style-type:none;">百盛</li>
<li style="list-style-type:none;">家乐福</li>
<li style="list-style-type:none;">新玛特</li>
<li style="list-style-type:none;">其他</li>
</div>
</body>
<script>
window.onload = function () {
var selectInput = document.getElementById('selectInput');
//var inputvalue = selectInput.value;
var optionLis = document.getElementById('optionLis');
var optionList = optionLis.children;
var arr= [];
optionLis.style.display = "none";
selectInput.onclick = function(){
if(optionLis.style.display == "none"){
optionLis.style.display = "block"
}else{
optionLis.style.display = "none"
}
}
//循环遍历li标签
for (var i=0;i<optionList.length;i++){
//li标签的点击事件
optionList[i].onclick = function (ev) {
//暂停其他的触发事件,阻止冒泡
ev.stopPropagation();
for (var i=0; i<arr.length;i++) {
if (arr[i] == this.innerHTML){
arr.splice(i,1);
selectInput.value = arr.join(',');
LiStyle();
return;
}
}
arr.push(this.innerHTML);
selectInput.value = arr.join(',');
LiStyle();
//选中时li标签的样式变化
function LiStyle() {
for (var i=0;i<optionList.length;i++){
optionList[i].style.background = '';
// var _a = optionList[i].querySelector("a");
// var _sp = _a.querySelector("span");
// _sp!=null && _a.removeChild(_sp);
}
var arr1 = selectInput.value.split(',');
for (var i=0;i<arr1.length;i++) {
for (var j=0;j<optionList.length;j++){
if (arr1[i] == optionList[j].innerHTML){
optionList[j].style.background = 'red';
// var _a = optionList[j].querySelector("a");
// var _sp = document.createElement("span");
// _sp.style.float= "right";
// _sp.className = "glyphicon glyphicon-ok";
// _sp.innerHTML="OK";
// _a.appendChild(_sp);
}
}
}
}
}
}
}
</script>
</html>
实现效果: