JS模拟select下拉菜单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS模拟select下拉菜单</title> <style> body{ font-size: 15px;} em{ font-style: normal;} ul{ padding: 0; margin: 0; list-style: none;} #box{ position: relative;} .select{ display: inline-block; border: 1px solid #ccc; padding: 5px; width: 10%; cursor: pointer;} .arrow{ color: #888; position: relative; left: -25px;} .sub{ display: none; border: 1px solid #ccc; border-top: none; border-bottom: none; width: 10.5%;} .sub li{ border-bottom: 1px solid #ccc; padding: 5px; cursor: pointer;} .sub li:hover ,.sub li.hover{ background: #eee;} </style> </head> <body> <h3>JS模拟selec下拉菜单</h3> <div id="box"> <form action=""> <span class="select">请选择下拉列表项</span><em class="arrow">▼</em> <button type="submit">搜索</button> </form> <ul class="sub"> <li>项目1</li> <li>项目2</li> <li>项目3</li> <li>项目4</li> <li>项目5</li> <li>项目6</li> <li>项目7</li> <li>项目8</li> </ul> </div> <script> window.onload = function(){ var oBox = document.getElementById('box'); var oSel = oBox.getElementsByTagName('span')[0]; var oSub = oBox.getElementsByTagName('ul')[0]; var oEm = oBox.getElementsByTagName('em')[0]; var aLi = oSub.getElementsByTagName('li'); // 点击显示隐藏下拉列表 oSel.onclick = function(ev){ var oEvent = ev || event; if(oSub.style.display == 'block'){ oEm.innerHTML = "▼"; // alert(oEm.innerHTML); oSub.style.display = 'none'; }else{ oEm.innerHTML = "▲"; oSub.style.display = 'block'; } // 阻止默认事件 oEvent.cancelBubble = true; }; // 点击文档任意空白处,隐藏下拉菜单 document.onclick = function(){ oSub.style.display = 'none'; }; // 循环遍历所有li,为每个li添加相应事件 for(var i = 0; i < aLi.length; i++){ // 鼠标移入,给li添加hover类 aLi[i].onmouseover = function(){ this.className = 'hover'; }; // 鼠标移出,移出li的class aLi[i].onmouseout = function(){ this.className = ''; }; // 点击li,将oSel的内容替换成当前li的值 aLi[i].onclick = function(){ oEm.innerHTML = "▼"; oSel.innerHTML = this.innerHTML; }; } }; </script> </body> </html>
运用到js的display显示隐藏、阻止默认事件,添加删除class,innerHTML等相关知识点。
代码只实现了它的功能,美化方面,可根据项目实际需要,自行调整修改。