纯CSS可点击的下拉菜单? [英] Pure CSS clickable dropdown?

查看:63
本文介绍了纯CSS可点击的下拉菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本教程介绍了如何使用:hover伪类进行样式设置将鼠标悬停在HTML元素上,以及如何将鼠标悬停在纯CSS中的特定元素上时如何创建下拉列表(不使用任何JavaScript).

This tutorial explains how to use the :hover pseudo-class to style HTML elements on hover and how to how create a dropdown when hovering over a particular element in pure CSS (without using any JavaScript).

是否可以在纯CSS中创建与以下示例中相同的下拉菜单,但是单击元素而不是将其悬停在元素上?

Is it possible to create the same dropdown as the one in the example below, in pure CSS, but when clicking an element instead of when hovering over it?

我宁愿完全不使用JavaScript,或者-如果没有JavaScript,则尽可能不使用-尽可能少使用JavaScript.淹没的物品应该可以自己点击.

I would prefer to use no JavaScript at all, or - if not possible without JavaScript - as little JavaScript as possible. The items of the drowndown should be clickable themselves.

.dropdown {
    position: relative;
    display: inline-block;
}

.dropbtn {
    background-color: #4CAF50;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
}

.dropdown-content {
    display: none;
    position: absolute;
    right: 0;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
    display: block;
}

.dropdown:hover .dropbtn {
    background-color: #3e8e41;
}

<div class="dropdown" style="float:left;">
  <button class="dropbtn">Left</button>
  <div class="dropdown-content" style="left:0;">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

推荐答案

在这里,您使用的是隐藏的复选框,并在选中"菜单时显示菜单.

Here you are using a hidden checkbox, and showing the menu when it is "checked".

/*hide the inputs/checkmarks and submenu*/
input, ul.submenu {
  display: none;
}

/*position the label*/
label {
  position: relative;
  display: block;
  cursor: pointer;
}

/*show the submenu when input is checked*/
input:checked~ul.submenu {
  display: block;
}

<input id="check01" type="checkbox" name="menu" />
<label for="check01">Menu</label>
<ul class="submenu">
  <li><a href="#">Item 1</a></li>
  <li><a href="#">Item 2</a></li>
</ul>

来自此Codepen 并经过简化.

这篇关于纯CSS可点击的下拉菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆