var oShow = document.getElementById('selected'),
oUl = document.getElementById('list'),
ev = event || window.event,
arr = [],
aLi = oUl.getElementsByTagName('li');
document.onclick = function () {
oUl.style.display = 'none';
//清空上次选中的选项
arr = [];
}
oShow.onclick = function (ev) {
oUl.style.display = 'block';
//触发了document的onclick事件,oUl无法显示,需要取消事件捕获
ev.stopPropagation();
}
for (let i = 0; i < aLi.length; i++) {
aLi[i].onclick = function (ev) {
if (ev.shiftKey) {
ev.stopPropagation();
ev.returnValue=false;
}
for (let j = 0; j < arr.length; j++) {
if (arr[j] == this.innerHTML) {
arr.splice(j, 1);
oShow.innerHTML = arr.join(',');
setBgColor();
return;
}
}
arr.push(this.innerHTML);
oShow.innerHTML = arr.join(',');
setBgColor();
}
//将被选中的li的背景和字体颜色设置高亮
function setBgColor() {
for (let j = 0; j < aLi.length; j++) {
aLi[j].className = '';
}
var arr1 = oShow.innerHTML.split(',');
for (let i = 0; i < arr1.length; i++) {
for (let j = 0; j < aLi.length; j++) {
if (arr1[i] == aLi[j].innerHTML) {
aLi[j].className = 'active';
}
}
}
}
}
}
用了ev.preventDefault(),return fasle等N种办法都不可以,这是为什么??求教,研究很久了...
试试在CSS里加上
user-select: none;