如何解决悬停

时间:2019-10-27 10:57:08

标签: html css

我当时正在做作业,而现在停留在实现悬停功能上。如果我只有1个按钮和1个面板,则一切正常,但是当我添加第2个按钮时,一切都将完全中断。

我尝试替换位置:绝对,编辑边距,但无济于事。

.block {
  width: 600px;
  height: 500px;
  border-style: solid;
  border-width: 4px;
}

.btn-1 {
  width: 296px;
  height: 163px;
  border-style: solid;
  border-width: 2px;
  background-color: #d63;
  z-index: 4;
  position: absolute;
  border-color: black;
}

.btn-2 {
  width: 296px;
  height: 163px;
  border-style: solid;
  border-width: 2px;
  background-color: #d63;
  z-index: 4;
  position: absolute;
  border-color: black;
  margin-top: 164px;
}

.panel {
  width: 300px;
  height: 500px;
  background-color: #d63;
  z-index: 3;
  position: absolute;
  transition: 0.7s;
}

.btn-1:hover+.panel {
  margin-left: 300px;
}
<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <div class="block">
      <button class="btn-1"> </button>
      <button class="btn-2"> </button>
      <div class="panel"> </div>
    </div>
  </div>
</body>

</html>

我希望第二个按钮不会破坏所有内容,并且悬停将正常工作。

1 个答案:

答案 0 :(得分:1)

在第二个按钮之间添加第二个按钮时,第一个按钮和面板不再adjacent siblings+操作符)。改用general sibling combinator~

.btn-1:hover~.panel {
  margin-left: 300px;
}

示例:

.block {
  width: 600px;
  height: 500px;
  border-style: solid;
  border-width: 4px;
}

.btn-1 {
  width: 296px;
  height: 163px;
  border-style: solid;
  border-width: 2px;
  background-color: #d63;
  z-index: 4;
  position: absolute;
  border-color: black;
}

.btn-2 {
  width: 296px;
  height: 163px;
  border-style: solid;
  border-width: 2px;
  background-color: #d63;
  z-index: 4;
  position: absolute;
  border-color: black;
  margin-top: 164px;
}

.panel {
  width: 300px;
  height: 500px;
  background-color: #d63;
  z-index: 3;
  position: absolute;
  transition: 0.7s;
}

.btn-1:hover~.panel {
  margin-left: 300px;
}
<!DOCTYPE html>
<html lang="">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <div class="block">
      <button class="btn-1"> </button>
      <button class="btn-2"> </button>
      <div class="panel"> </div>
    </div>
  </div>
</body>

</html>