一、開發小要點
web頁面中,我們一般不用select、option來實現下拉菜單效果,因為下拉框的樣式丑且難以美化,所以我們選擇控制ul顯示隱藏來實現同樣且高大上的效果,但是不能像下拉框那樣點擊頁面其他部分,下拉菜單收起或隱藏,該怎么辦呢?只能用js這老大哥來控制了。
二、代碼
HTML:
<div class="select_box" id="selected">
<div class="select">
<span>請選擇</span>
</div>
<ul class="list">
<li>01</li>
<li>02</li>
<li>03</li>
<li>04</li>
</ul>
</div>
CSS:
<style type="text/css"> *{margin:0;padding:0} ul,ol{list-style: none} .select_box{ position:relative; margin:100px auto; width:300px;
} .select{ padding:5px 10px; border:1px solid #dedede;
} .select:hover{ cursor:pointer;
} .select span{ display: block; background:url("../../img/downicon.png") no-repeat right;
} .list{ display: none; position:absolute; top:30px; width:298px; border:1px solid #dedede; border-top:none;
} .list li{ padding:5px 10px;
} .list li:hover{ background:#ddd;
} </style>
JS:
$(function(){ $(".select").click(function(){ $(".list").toggle(); }) $(".list li").click(function(){ $(".select span").html($(this).html()); $(".list").hide(); }) $(document).bind("click",function(e){ var e = e || window.event; //事件對象,兼容IE
var target = e.target || e.srcElement; //源對象,兼容火狐和IE
while(target){ if (target.id && target.id == "selected"){ //循環判斷至根節點,防止點擊的是#selected和它的子元素
return; } target = target.parentNode; } $(".list").hide(); //點擊的不是#selected和它的子元素,隱藏下拉菜單
}) })
效果: