我有一个问题,无法解决。
我已经创建了此HTML页面,但是:hover上的#drop选择器不起作用。



#drop {
    display: inline-block;
    color: white;
    background-color: #4CAF50;
    padding: 10px;
}
#droplist {
    display: none;
    position: absolute;
    z-index: 1;
}
#droplist a {
    display: block;
    text-decoration: none;
    color: white;
    background-color: olivedrab;
    padding: 10px;
}
#drop:hover #droplist {
    display: block;
}
#droplist a:hover {
    background-color: olive;
}

<!DOCTYPE html>
<html lang="it">
<!--   ...   -->
<body>
    <div id="pagina">
        <div id="drop">Hover for open the menu</div>
        <div id="droplist">
            <a href="#a">Link 1</a>
            <a href="#b">Link 2</a>
            <a href="#c">Link 3</a>
        </div>
        <br/>text text text text text text text text text
    </div>
</body>
</html>





我尝试将鼠标悬停在ID为#drop的div上,但是元素#droplist没有显示。

最佳答案

您不能选择#drop:hover #droplist,因为#droplist不是#drop的子级。

请改用#drop:hover + #droplist

element1 + element2选择器用于选择和设置紧随element2之后的每个element1的样式



#drop {
  display: inline-block;
  color: white;
  background-color: #4CAF50;
  padding: 10px;
}

#droplist {
  display: none;
  position: absolute;
  z-index: 1;
}

#droplist a {
  display: block;
  text-decoration: none;
  color: white;
  background-color: olivedrab;
  padding: 10px;
}

#drop:hover+#droplist {
  display: block;
}

#droplist a:hover {
  background-color: olive;
}

#droplist:hover {
  display: block
}

<!DOCTYPE html>
<html lang="it">
<!--   ...   -->

<body>
  <div id="pagina">
    <div id="drop">Hover for open the menu</div>
    <div id="droplist">
      <a href="#a">Link 1</a>
      <a href="#b">Link 2</a>
      <a href="#c">Link 3</a>
    </div>
  </div>
</body>

</html>





编辑:您可能要添加

#droplist:hover {
   display: block
}


这样,当您将鼠标悬停在下拉菜单上时,该菜单不会消失

10-06 00:05