【问题标题】:why the dropdown menu is not showing when I hover on the span?为什么当我悬停在 span 上时下拉菜单没有显示?
【发布时间】:2022-12-17 13:15:29
【问题描述】:

当我将鼠标悬停在跨度上时,下拉菜单未显示

.user {
  position: relative;
  top: 9px;
  margin-left: 50px;
}

.user .user-name {
  position: relative;
  top: -20px;
  margin-left: 25px;
  color: #1E1E2D;
}

.user .user-name::before {
  content: "";
  border: 5px solid transparent;
  width: 5px;
  height: 10px;
  border-top-color: black;
  position: relative;
  top: 14px;
  left: -3px;
}

.user span:hover .user-list {
  display: block;
}

.user ul {
  position: absolute;
  background-color: white;
  top: 45px;
  left: 70px;
  width: 200px;
  padding: 18px;
  box-shadow: -6px 13px 20px 8px #eee;
  display: none;
  list-style-type: none;
  z-index: 1;
}
<div class="nav">
  <div class="user">
    <img src="assest/user.png" alt="" srcset="">
    <span id="show" class="user-name">Name</span>
    <ul class="user-list">
      <li><a href="">Home</a></li>
      <li><a href="">Account</a></li>
      <li><a href="">LogOut</a></li>
    </ul>
  </div>
</div>

我原以为当我将鼠标悬停在跨度上时会显示下拉菜单,但它没有发生。 我试图用“div”或“p”替换“span”,但它也不起作用。

【问题讨论】:

  • 但是如果你希望触发器是那个确切的跨度,你应该使用像.user span:hover + .user-list这样的选择器,因为 .userlist 是兄弟而不是后代

标签: html css web


【解决方案1】:

这是因为您的 .user-list 不在 span 元素内,而是在类为 .user 的 div 内

改变

.user span:hover .user-list {

经过

.user:hover .user-list {

.user {
  position: relative;
  top: 9px;
  margin-left: 50px;
}

.user .user-name {
  position: relative;
  top: -20px;
  margin-left: 25px;
  color: #1E1E2D;
}

.user .user-name::before {
  content: "";
  border: 5px solid transparent;
  width: 5px;
  height: 10px;
  border-top-color: black;
  position: relative;
  top: 14px;
  left: -3px;
}

.user:hover .user-list {
  display: block;
}

.user ul {
  position: absolute;
  background-color: white;
  top: 45px;
  left: 70px;
  width: 200px;
  padding: 18px;
  box-shadow: -6px 13px 20px 8px #eee;
  display: none;
  list-style-type: none;
  z-index: 1;
}
<div class="nav">
  <div class="user">
    <img src="assest/user.png" alt="" srcset="">
    <span id="show" class="user-name">Name</span>
    <ul class="user-list">
      <li><a href="">Home</a></li>
      <li><a href="">Account</a></li>
      <li><a href="">LogOut</a></li>
    </ul>
  </div>
</div>

【讨论】:

    【解决方案2】:

    当用户将鼠标悬停在 .user-name 元素上时,您似乎正试图显示 .user-list 元素。但是,CSS 选择器 .user span:hover .user-list 不正确。

    :hover 伪类仅适用于选择器中紧接其前面的元素。在这种情况下,:hover 伪类应用于 span 元素,但 .user-list 元素不是 span 元素的直接子元素。

    要解决此问题,您可以在 CSS 选择器中使用 > 符号来指示 .user-list 元素是悬停在其上的 span 元素的直接子元素。例如:

    .user span:hover > .user-list {
      display: block;
    }
    

    当用户将鼠标悬停在作为 .user 元素的直接子元素的 span 元素上时,此选择器会将 display: block 样式应用于 .user-list 元素。

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 2018-02-09
      • 2013-04-21
      • 2015-11-30
      相关资源
      最近更新 更多