过渡不适用于下拉菜单

时间:2021-05-29 09:56:21

标签: html css css-transitions

我正在尝试将转换应用到我的下拉列表中,但它不起作用。悬停后立即出现下拉菜单,效果不可见。

.dropdown {
  position: relative;
  display: inline-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);
  padding: 12px 16px;
  z-index: 1;
  transform: translateY(-170px);
  transition: all 1s;
}

.dropdown:hover>.dropdown-content {
  display: block;
  background-color: yellowgreen;
  transform: translateY(20px);
}
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the text below to open the dropdown content.</p>
<div class="dropdown">
  <div class="dropdown-content">
    <p>Hello World!</p>
  </div>
  <span>Mouse over me</span>
</div>

1 个答案:

答案 0 :(得分:0)

display 属性不可设置动画。您可以为 opacity 设置动画。
您可以将 display 默认为 block

<html>
  <head>
    <style>
      .dropdown {
        position: relative;
        display: inline-block;
      }
      .dropdown-content {
        display: block;
        position: absolute;
        background-color: #f9f9f9;
        min-width: 160px;
        box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
        padding: 12px 16px;
        z-index: 1;
        opacity: 0;
        transform: translateY(-170px);
        transition: all 1s;
      }
      .dropdown:hover > .dropdown-content {
        opacity: 1;
        background-color: yellowgreen;
        transform: translateY(20px);
      }
    </style>
  </head>
  <body>
    <h2>Hoverable Dropdown</h2>
    <p>Move the mouse over the text below to open the dropdown content.</p>
    <div class="dropdown">
      <div class="dropdown-content">
        <p>Hello World!</p>
      </div>
      <span>Mouse over me</span>
    </div>
  </body>
</html>