在这个例子中,我们会看到一个纯CSS制作的下拉框。主要是要用到了HTML元素的checkbox 和CSS3选择器,并没有用到JavaScript。例子如下:
<!–
.dropdown *{padding: 0;margin: 0;}
.dropdown{
position: relative;
display: inline-block;
font-size: 16px;
color: #FFF;
height:300px;
}
.dropdown input[type=”checkbox”]{display: none;}
.dropdown label{
box-sizing: border-box;
display: inline-block;
width: 100%;
background-color: #57A0D4;
padding: 15px 20px;
cursor: pointer;
text-align: center;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* The ul will have display:none by default */
.dropdown ul{
position: absolute;
list-style: none;
list-style-type:none !important;
text-align: left;
width: 100%;
z-index: 1;
margin:0 !important;
padding:0;
box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.2);
display: none;
}
.dropdown ul li{
list-style: none;
padding: 15px;
background-color: #fff;
color: #4FB9A7;
margin-bottom: 1px;
cursor: pointer;
}
.dropdown ul li:hover{
background-color: #4FB9A7;
color: #FFF;
}
.dropdown ul li a{
color: inherit;
text-decoration: none;
}
.dropdown input[type=checkbox]:checked ~ label {
background-color: #3D88BD;
}
.dropdown input[type=”checkbox”]:checked ~ ul{
display: block;
}
–>
Click to Expand
实现过程:
HTML结构
<div class="dropdown">
<input type="checkbox" id="checkbox_toggle">
<label for="checkbox_toggle">Click to Expand</label>
<ul>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link One</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link Two</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link Three</a></li>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link Four</a></li>
</ul>
</div>
#div作为一个容器包裹所有标签
#input[type=checked]标签用于标识checked 和unchecked 属性,元素是隐藏的
#label标签用于触发下拉菜单
#ul为菜单列表
添加Checkbox Hack
我们只需要checkbox元素的伪类选择器:checked就可以检测到元素的checked状态,通过label标签来触发checkbox的unchecked 和checked 状态。首先把checkbox隐藏
input[type=checkbox]{
display: none;
}
同时,我们也把ul默认隐藏掉,当触发菜单时才会显示。
ul{
display: none;
}
通过结合:checked选择器 和相邻同胞选择器~ 来控制对应的菜单的显示状态。
input[type=checkbox]:checked ~ ul {
display: block
}
当checkbox为选中状态时,下拉菜单就显示,否则隐藏。
demo: