1.通过hover,也是最常用的方式。此方法要求按钮与被控制元素必须有层级关系。(兼容低端浏览器常用)
<div class="nav-btn"> <h2>按钮</h2> <ul class="nav-box"> <li><a href="#">菜单1</a></li> <li><a href="#">菜单2</a></li> <li><a href="#">菜单3</a></li> </ul> </div>
*{ padding: 0; margin: 0; } ul,li{ list-style: none; } .nav-btn{ position: relative; } .nav-btn h2{ height: 60px; line-height: 60px; width: 130px; text-align:center; background: #ff0; } .nav-box{ position: absolute; top:60px; left: 0px; display: none; } .nav-btn:hover .nav-box{ display: block; }
2.通过:focus点击按钮显示,点击空白处隐藏。此方通同样需要按钮与被控制元素之间存在层级关系。(需用到CSS3选择器)
<div class="nav-btn"> <button>按钮</button> <ul class="nav-box"> <li><a href="#">菜单1</a></li> <li><a href="#">菜单2</a></li> <li><a href="#">菜单3</a></li> </ul> </div>
*{ padding: 0; margin: 0; } ul,li{ list-style: none; } .nav-btn{ position: relative; } .nav-btn h2{ height: 60px; line-height: 60px; width: 130px; text-align:center; background: #ff0; } .nav-box{ position: absolute; top:60px; left: 0px; display: none; } .nav-btn button:focus ~ .nav-box{ display: block; }
3.利用label的for属性绑定checkbox,此方法对按钮与盒子的层级关系没有限制(需用到CSS3选择器)
<label for="control" class="nav-btn">菜单</label> <div> <input type="checkbox" name="" id="control" class="nav-con"> <ul class="nav-box"> <li><a href="#">首页</a></li> <li><a href="#">联系我们</a></li> <li><a href="#">产品</a></li> <li><a href="#">新闻</a></li> </ul> </div>
ul,li{ list-style: none; } *{ padding: 0; margin: 0; } .nav-con{ display: none; } .nav-box{ display: none; } .nav-con:checked ~ .nav-box{ display: block; } .nav-btn{ padding: 10px 15px; background:; }