使下拉菜单多级化
P粉107772015
P粉107772015 2024-01-10 18:02:08
0
2
460

我有一个下拉菜单,如下所示:

.dropdown
{
    display: inline-block;
    position: relative;
}
.dropdown button > a
{
    display: block;
    color: #000000;
    text-decoration: none;
}
.dropdown-content
{
    display: none;
    position: absolute;
    width: auto;
    overflow: auto;
    box-shadow: 0px 10px 10px 0px rgba(0,0,0,0.4);
}
.dropdown:hover .dropdown-content
{
    display: block;
}
.dropdown-content a
{
    display: block;
    color: #000000;
    background-color: #e9e9ed;
    padding: 5px;
    text-decoration: none;
}
.dropdown-content a:hover
{
    color: #FFFFFF;
    background-color: #0080bf;
}
<DIV class="dropdown"><BUTTON>Menu</BUTTON><DIV class="dropdown-content">
    <A href="/1.php">Option 1</A>
    <A href="/2.php">Option 2</A>
    <A href="/3.php">Option 3</A>
    <DIV class="dropdown"><BUTTON><A href="/4.php">Option 4</A></BUTTON><DIV class="dropdown-content">
        <A href="/4-1.php">Option 4-1</A>
        <A href="/4-2.php">Option 4-2</A>
        <A href="/4-3.php">Option 4-3</A>
    </DIV></DIV>
</DIV></DIV>
但第二级菜单不起作用(按“运行代码片段”即可查看)。我需要它显示在第一级的右侧,并且每级的宽度必须是弹性的(根据内容自动增加和减少)。此外,根按钮的宽度不得绑定到第一级的宽度。理想情况下,任何级别都应该有通用风格,但这并不重要,因为我没有数十个级别。有没有不用重写所有代码的解决方案?

P粉107772015
P粉107772015

全部回复(2)
P粉235202573

雷雷 雷雷
P粉187160883

您可以执行以下操作:

.dropdown-content 中删除 overflow: auto;,以便溢出的子级别可见。在 .dropdown:hover .dropdown-content 行添加 > 选择器,以便直接子项将在悬停时显示。最后一件事是添加子级别样式以将其显示在右上角 .dropdown-content .dropdown-content { left: 100%;顶部:0; }

body {
  background-color: antiquewhite;
}
.dropdown
{
    display: inline-block;
    position: relative;
    width: 100%;
}
.dropdown-content
{
    display: none;
    position: absolute;
    width: auto;
    box-shadow: 0px 10px 10px 0px rgba(0,0,0,0.4);
    white-space: nowrap;
}
.dropdown:hover > .dropdown-content
{
    display: block;
}
.dropdown-content a
{
    display: block;
    color: #000000;
    background-color: #e9e9ed;
    padding: 5px;
    text-decoration: none;
}
.dropdown-content a:hover
{
    color: #FFFFFF;
    background-color: #0080bf;
}

/* To display second level on right*/
.dropdown-content .dropdown-content {
    left: 100%;
    top: 0;
}
<div class="dropdown">
    <div class="menu">Menu</div>
    <div class="dropdown-content">
      <a href="/1.php">Option 1 Longer</a>
      <div class="dropdown">
          <div class="menu">
            <a href="/4.php">Option</a>
          </div>
          <div class="dropdown-content">
            <a href="/4-1.php">Option 4-1</a>
            <a href="/4-2.php">Option 4-2</a>
            <a href="/4-3.php">Option 4-3</a>
        </div>
      </div>
    </div>
</div>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板