我构建了一个带有下拉菜单的水平导航栏,该菜单应该在将鼠标悬停在其所在的按钮/链接上时显示,并在鼠标向下移动到下拉菜单本身时保持显示。下拉菜单始终显示在主导航栏上的按钮/链接悬停时,但是当将鼠标从主水平导航栏向下移动到下拉菜单本身时,我遇到了下拉菜单的显示问题。我在 Chrome 和 Edge 中尝试过 - 它通常适用于第一次鼠标悬停,但一旦鼠标移到其所在的按钮/链接下方,下拉菜单就会开始消失。
我在 Windows 11 计算机上使用 Visual Studio Code 来编写所有内容。
这是 HTML 代码:
<!DOCTYPE html>
<html lang="en">
<!-- CaseStudy_Homepage -->
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="CaseStudy.css"/>
<title>OPE ID Lookup and FICE Crosswalk: Homepage</title>
</head>
<body>
<div class="topnav" id="myTopnav">
<a id="active">Home</a>
<div class="dropdown">
<button class="dropbtn"><a href="SearchMenu.html">Search Options</a></button>
<div class="dropdown-content">
<a href="Fice.html">OPE ID code by FICE code</a>
<a href="Search.html">OPE ID code by Institutional Information</a>
<a href="VerifySearch.html">Verify OPE ID code</a>
</div>
</div>
<a href="DataDictionary.html">Data Dictionary</a>
</div>
这是导航栏的 CSS:
/* Navigation Bar */
/* Add a black background color to the top navigation */
.topnav {
height: 48.8px;
background-color: black;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 18px;
font-weight: bold;
line-height: normal;
margin: 0;
}
/* Add an active class to highlight the current page */
#active, #active a:hover {
background-color: inherit;
text-decoration: underline;
}
/* Dropdown container - needed to position the dropdown content */
.dropdown {
float: left;
overflow: hidden;
}
/* Style the dropdown button to fit inside the topnav */
.dropdown .dropbtn {
font-size: 18px;
font-weight: bold;
border: none;
outline: none;
color: white;
text-align: center;
background-color: inherit;
font-family: inherit;
margin: 0;
}
/* Style the dropdown content (hidden by default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Style the links inside the dropdown */
.dropdown-content a {
float: none;
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
/* Add a dark background on topnav links and the dropdown button on hover */
.topnav a:hover, .dropdown:hover .dropbtn {
background-color: #555;
color: white;
}
/* Add a grey background to dropdown links on hover */
.dropdown-content a:hover {
background-color: #ddd;
color: black;
}
/* Show the dropdown menu when the user moves the mouse over the dropdown button */
.dropdown:hover .dropdown-content {
display: block;
}
有人看到或知道为什么它会这样吗?
要解决这个问题,只需将下拉内容向上移动一点即可。
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
transform: translateY(-5px); // <-- this part is the solution
}
下拉菜单无法正常工作的原因是
.dropdown
元素和 .dropdown-content
元素之间有一个小间隙。
因此,一旦您将鼠标移到内容上,这些元素都不会悬停,并且下拉菜单会关闭。