悬停按钮显示div隐藏的CSS

时间:2019-03-15 09:58:13

标签: css

我有一个简单的按钮,上面有一个div,这是不可见的:

<button class="dropbtn">
    <i class="fas fa-plus"></i>
</button>
<div class="dropdown-content">
    some content here ... hidden 
</div>

我希望在鼠标悬停时显示下拉菜单内容。我写了这些课:

.dropdown-content {
    display: none;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1;
}
.dropbtn:hover .dropdown-content {
    display:block !important;
} 

也许我错过了某件事...

3 个答案:

答案 0 :(得分:3)

在我制作的片段中添加css代码中的+(添加+,因为要显示的div在按钮div之后,如果将悬停div放在按钮div内,css将起作用),可以相应地添加更多的CSS。

.dropdown-content {
    display: none;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1;
}
.dropbtn:hover + .dropdown-content {
    display:block !important;
} 
<button class="dropbtn">Button
    <i class="fas fa-plus"></i>
</button>
<div class="dropdown-content">
    some content here ... hidden 
</div>

答案 1 :(得分:1)

使用+选择器将css应用于元素,同时将鼠标悬停在其他元素上

.dropdown-content {
    display: none;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 1;
}
.dropbtn:hover + .dropdown-content {
    display:block !important;
} 
<button class="dropbtn">
    <i class="fas fa-plus"></i>
</button>
<div class="dropdown-content">
    some content here ... hidden 
</div>

答案 2 :(得分:0)

我在W3Schools(这里是https://www.w3schools.com/howto/howto_js_dropdown.asp)上找到了一个替代方案:

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

和CSS:

/* Dropdown Button */
.dropbtn {
  background-color: #3498DB;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
  background-color: #2980B9;
}

/* The container <div> - needed to position the dropdown content */
.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f1f1f1;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #ddd}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}