【问题标题】:CSS transition only on not activeCSS 过渡仅在不活动时
【发布时间】:2018-10-16 16:59:52
【问题描述】:

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

#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?

【问题讨论】:

  • 你能给我们看看你的html吗
  • 这里是场景的 jsfiddle jsfiddle.net/ewtmc6kg
  • 不要认为这在 CSS 中是可能的。您希望以两种不同的方式处理进入一种状态(“正常”状态),具体取决于它是从哪个状态进入的——但在 CSS 中没有办法区分。

标签: css css-transitions


【解决方案1】:

您可以使用: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>

【讨论】:

  • 你的意思是什么?
  • 理论上可以,但实际上不行,因为 #el:not(:active):hover 与 #el:hover 相同,当您悬停时会导致条目转换。在您对我的问题的评论中添加了一个 jsfiddle
  • 我觉得一定要用js或者jquery
【解决方案2】:

您可以使用伪元素来模拟这一点,您将能够管理两种不同的东西。悬停会改变背景,活动状态会改变伪元素:

#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>

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 2015-06-22
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多