如何在按钮上分开双悬停?

时间:2019-01-06 12:42:34

标签: html css button hover

我想知道是否有类似的线程,但是找不到。

我的按钮上有两个悬停事件。我想要实现的是:当我将close以外的所有内容都悬停时,整个按钮(关闭除外)会变成灰色,而当我将close悬停时,其整个按钮(仅)会变成黑色。

您会注意到,当我将鼠标悬停在close(红色)上时,会出现两个悬停。按钮变为灰色,close为黑色。我需要将这两个悬停分开。

Live example

代码:

HTML

<div class="panel">
  <div class="btn">
    <span class="text">Description 1</span>
    <div class="close"></div>
  </div>

  <div class="btn">
    <span class="text">Description 2</span>
    <div class="close"></div>
  </div>

</div>

CSS

.panel {
  display: flex;
  flex-direction: row;
}

.btn {
  display: flex;
  width: 120px;
  height: 20px;
  border: 2px solid black;
  margin-left: 10px;
}

.btn:hover {
  background: rgba(189, 195, 199, 1)
}

.close {
  width: 30px;
  height: 100%;
  background: red;
  justify-content: flex-end;
}

.close:hover {
  background: black;
}

1 个答案:

答案 0 :(得分:1)

您可以在关闭按钮中使用伪元素来隐藏父悬停上的黑色背景:

.panel {
  display: flex;
  flex-direction: row;
}

.btn {
  display: flex;
  width: 120px;
  height: 20px;
  border: 2px solid black;
  margin-left: 10px;
  position:relative;
  z-index:0;
}

.btn:hover {
  background: rgba(189, 195, 199, 1)
}

.close {
  width: 30px;
  height: 100%;
  background: red;
  justify-content: flex-end;
}

.close:hover {
  background: black;
}
.close:hover::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:#fff;
}
<div class="panel">
  <div class="btn">
    <span class="text">Description 1</span>
    <div class="close"></div>
  </div>
  
  <div class="btn">
    <span class="text">Description 2</span>
    <div class="close"></div>
  </div>

</div>