jQuery点击页面其他部分隐藏下拉菜单


一、开发小要点

    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和它的子元素,隐藏下拉菜单
 }) })

    效果:

    


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM