簡單模擬select裡的多選操作和shift的多選
阿新 • • 發佈:2019-01-26
效果展示:
html部分:
<div class="w"> <div class="single"> <div class="nav">單選</div> <div class="content"> <div class="show"></div> <ul class="hide"> <li>北京</li> <li>上海</li> <li>廣州</li> <li>杭州</li> <li>鄭州</li> </ul> </div> </div> <div class="many"> <div class="nav">多選</div> <div class="content"> <div class="show">按住shift進行多選操作</div> <ul class="hide"> <li>北京</li> <li>上海</li> <li>廣州</li> <li>杭州</li> <li>鄭州</li> </ul> </div> </div> </div>
css部分:
<style type="text/css"> ul,li { padding: 0; margin: 0; list-style: none; } .w{ width: 1210px; margin:0 auto; text-align: center; position: relative; } .single,.many{ width: 400px; margin: 50px auto; float: left; position: absolute; top: 0; } .single{ left: 100px; } .many{ left: 700px; } .nav, .show, li { height: 30px; line-height: 30px; font-size: 20px; } .nav{ background: #ff931f; color: #ffffff; font-weight: 600; margin-bottom: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; } .show,ul{ border: 1px solid #ff931f; } .hide{ display: none; } .show { padding: 5px; } .hide li{ text-align: left; padding: 5px; cursor: pointer; } .hide li:hover{ color: #ffffff; background: #ff931f; } .hide li,.show li{ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; }
javaScript部分:
<script> window.onload = function () { var aShow = document.getElementsByClassName('show'); var aHide = document.getElementsByClassName('hide'); var arr= []; for (var i=0;i<aShow.length;i++) { aShow[i].index = i; aShow[i].onclick = function (ev) { var ev = ev || event; ev.cancelBubble = true; aHide[this.index].style.display = 'block'; } } //單選 singleFn(aShow[0],aHide[0]); function singleFn( show,hide) { var aLi = hide.getElementsByTagName('li'); for (var i=0;i<aLi.length;i++){ aLi[i].onclick = function () { show.innerHTML = this.innerHTML; hide.style.display = 'none'; } } } document.onclick = function () { aHide[1].style.display = 'none'; arr=[]; } //多選 for (var i=0;i<aHide[1].children.length;i++){ aHide[1].children[i].onclick = function (ev) { var ev = ev || event; if (ev.shiftKey) { ev.cancelBubble = true; } for (var i=0; i<arr.length;i++) { if (arr[i] == this.innerHTML){ arr.splice(i,1); aShow[1].innerHTML = arr.join(','); bgcolor(); return; } } arr.push(this.innerHTML); aShow[1].innerHTML = arr.join(','); bgcolor(); //控制多選裡的背景變化的函式 function bgcolor() { for (var i=0;i<aHide[1].children.length;i++){ aHide[1].children[i].style.background = ''; aHide[1].children[i].style.color = ''; } var arr1 = aShow[1].innerHTML.split(','); for (var i=0;i<arr1.length;i++) { for (var j=0;j<aHide[1].children.length;j++){ if (arr1[i] == aHide[1].children[j].innerHTML){ aHide[1].children[j].style.background = '#ff931f'; aHide[1].children[j].style.color = '#ffffff'; } } } } } } } </script>