js模拟select下拉菜单
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{width: 200px;height: 40px;line-height: 40px;text-indent: 5px;margin: 0 auto;}
.box span{display: block;border: solid 1px black;}
.list{margin: 0;padding: 0;list-style: none;background: #efefef;border: solid 1px black;border-top:0;display: none;}
.list li{line-height: 40px;text-indent: 20px;}
.list li.active{background: #66f;color: #fff;}
</style>
</head>
<body>
<div class="box">
<span class="title">北京</span>
<ul class="list">
<li>北京</li>
<li>上海</li>
<li>广州</li>
<li>深圳</li>
<li>杭州</li>
</ul>
</div>
<select name="" id="">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
<option value="杭州">杭州</option>
</select>
</body>
<script src="../public.js"></script>
<script>
var ospan = document.querySelector(".title");
var olist = document.querySelector(".list");
var ali = olist.children;
// 3.提前准备一个状态变量:1显示,2隐藏,默认为1显示
var type = 1;
// 9.默认项的索引
var index = 3;
setActive();
ospan.innerHTML = ali[index].innerHTML;
// 设置当前项
function setActive(){
// 先取消所有
for(var i=0;i<ali.length;i++){
ali[i].className = "";
}
// 给当前li加上
ali[index].className = "active";
}
// 1.点击内容区域显示
ospan.onclick = function(eve){
var e = eve || window.event;
stopBubble(e);
// 4.根据状态决定显示,或隐藏,同时修改状态
if(type === 1){
olist.style.display = "block";
// 12.每次显示下拉菜单,都渲染一次默认值
setActive();
type = 2;
}else{
olist.style.display = "none";
type = 1;
}
}
// 2.点击空白隐藏
document.onclick = function(){
olist.style.display = "none";
type = 1;
}
// 5.遍历li
for(var i=0;i<ali.length;i++){
// 10.给每个li绑定索引,起个名叫abc
ali[i].abc = i;
// 6.鼠标进入li
ali[i].onmouseover = function(){
index = this.abc;
setActive();
}
// 7.鼠标离开li
ali[i].onmouseout = function(){
// 取消当前li的样式
this.className = "";
}
// 8.鼠标点击li
ali[i].onclick = function(){
// 将span的内容设置成li的内容
ospan.innerHTML = this.innerHTML;
// 11.点击li后,将默认索引改成点击的索引
index = this.abc;
}
}
</script>
</html>