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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

crackedlove   2020-05-16 我要评论

一、开发小要点

    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("../../imghttps://img.qb5200.com/download-x/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和它的子元素,隐藏下拉菜单
    })
  })

    效果:

总结

以上所述是小编给大家介绍的jQuery点击页面其他部分隐藏下拉菜单功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们