CSS 仅在未激活时转换

CSS transition only on not active

我有一个场景,我需要在悬停时立即更改背景颜色,并在取消悬停时立即恢复为原始颜色。这很简单:

#el {
    background-color: black;
}
#el:hover {
    background-color: gray;
}

但是,我遇到了一个问题,我还需要立即更改活动背景颜色,但要在活动释放时使用过渡。

#el:active {
    background-color: green;
}

#el:hover:deactivate { /*does not exist*/
    background-color: gray;
    transition: background-color 1s ease;
}

#el:deactivate { /*does not exist either*/
    background-color: black;
    transition: background-color 1s ease;
}

我不能通过设置 #el:hover 来做到这一点,因为这样悬停条目也会得到动画,而我不能在 #el 本身上这样做,因为那时取消悬停也会得到动画。

有没有办法使用纯 CSS 而不使用 JS 来做到这一点?

您可以使用:not(:active)

#el:active {
    background-color: green;
}

#el:not(:active):hover {
    background-color: gray;
    transition: background-color 1s ease;
}

#el:not(:active) {
    background-color: black;
    transition: background-color 1s ease;
}
<a href="#" id="el">active</a>

您可以使用伪元素对此进行模拟,您将能够管理两种不同的事物。 hover会改变背景,active状态会改变伪元素:

#el {
  color: white;
  background-color: black;
  border: 1px solid white;
  height: 200px;
  width: 200px;
  position:relative;
  z-index:0;
}
#el:before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background:transparent;
  transition:1s;
}

#el:hover {
  background-color: gray;
}

#el:active::before {
  background: green;
  transition: 0s;
}
<div id="el">
  CONTENT HERE
</div>