CSS-如何创建下拉菜单

时间:2018-08-06 21:50:29

标签: html css

我创建了一个下拉菜单。效果很好,但是有一个我自己无法解决的问题。

.dropdown-toggle ~ .dropdown-menu {
        display: block;
        opacity: 0;
        -webkit-transition: all 200ms ease-in;
        -moz-transition: all 200ms ease-in;
        -ms-transition: all 200ms ease-in;
        -o-transition: all 200ms ease-in;
        transition: all 200ms ease-in;
      }
      .dropdown-toggle:hover ~ .dropdown-menu {
        display: block;
        opacity: 1;
      }
<ul class="navbar-nav">
    	<li class="dropdown">
    		<a class="dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">Test</a>
    		<div class="dropdown-menu"> 
    			<a class="dropdown-item" href="#">Test1</a> 
    			<a class="dropdown-item" href="#">Test2</a> 
    		</div>
    	</li>
    </ul>

如果我将鼠标悬停在菜单上-如果鼠标悬停在下拉切换类上,则该菜单有效。如果我将鼠标悬停在菜单上的元素上,整个菜单就会消失。

我知道我可以将 dropdown-toggle 更改为 dropdown ,但我想仅在鼠标悬停于.dropdown-toggle而不是整个容器上方时才激活菜单。

您知道如何执行此操作吗?

1 个答案:

答案 0 :(得分:1)

您要做的就是在CSS中添加另一个属性,该属性将显示链接-当您将鼠标悬停在链接上时:

.dropdown-toggle ~ .dropdown-menu:hover {
        display: block;
        opacity: 1;
        visibility: visible;
}

我添加的另一个属性是确保您首先将鼠标悬停在主链接上,然后用鼠标悬停在主链接上:

.dropdown-toggle ~ .dropdown-menu {
        visibility: hidden;
}

隐藏它们的可见性后,您将无法在它们上触发“悬停” css事件。

.dropdown-toggle ~ .dropdown-menu {
        display: block;
        opacity: 0;
        -webkit-transition: all 200ms ease-in;
        -moz-transition: all 200ms ease-in;
        -ms-transition: all 200ms ease-in;
        -o-transition: all 200ms ease-in;
        transition: all 200ms ease-in;
      }
      .dropdown-toggle:hover ~ .dropdown-menu, .dropdown-toggle ~ .dropdown-menu:hover {
        display: block;
        opacity: 1;
        visibility: visible;
      }
      .dropdown-toggle ~ .dropdown-menu {
        visibility: hidden;
      }
<ul class="navbar-nav">
    	<li class="dropdown">
    		<a class="dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">Test</a>
    		<div class="dropdown-menu"> 
    			<a class="dropdown-item" href="#">Test1</a> 
    			<a class="dropdown-item" href="#">Test2</a> 
    		</div>
    	</li>
    </ul>