html - 在一个方向而不是另一个方向运行 CSS 过渡

标签 html css css-transitions

我在我的超链接元素上使用 CSS 过渡,使它们的交互看起来更流畅。但我也希望在用户等待时立即得到反馈。因此,我希望新状态立即出现,但当用户离开时让它淡出。

这是我目前正在使用的一些 CSS:

a
{
  display: inline-block;
  padding: 20px;
  background: #eeeeee;
  color: black;
  text-decoration: none;
  transition: background 1s;
}
a:hover
{
  background: #bbbbbb;
  transition: background 0s;
}
a:active
{
  background: #888888;
  transition: background 0s;
}
<a href="javascript:void(0)">Test link</a>

如您所见,当鼠标光标离开元素时,颜色渐变会生效,但进入元素时则不会。

在悬停的链接上按下鼠标按钮时,颜色会再次立即改变。

现在是有趣的部分:当鼠标按钮被释放时,我希望颜色淡回到悬停状态。但我无法做到这一点,因为 :hover 状态不知道它来自哪个状态方向,并且总是禁用转换。

无论发生什么变化,第一次悬停链接时都不能有任何过渡。

还是简单的状态图:

State:          normal   <---------->   hover   <---------->   active
Transition:             yes         no         yes?        no
                                          (currently no)

这可以用 CSS 实现吗?我知道我可以添加自定义 JavaScript,但这需要处理大量元素。

最佳答案

一个想法是使用伪元素来创建你的背景,你可以很容易地创建你想要的效果。缺点是您将拥有更多 CSS,并且必须将内容添加到 span 中才能正确设置 z-index 值。

使用 2 个伪元素:

a {
  display: inline-block;
  padding: 20px;
  background: #eeeeee;
  color: black;
  text-decoration: none;
  transition: background 1s;
  position: relative;
}

a span {
  position: relative;
  z-index: 3;
}

a:before,
a:after {
  content: "";
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: transparent;
  z-index: 1;
  transition: background 1s;
}

a:after {
  z-index: 2;
}

a:hover::before {
  background: red;
  transition: background 0s;
}

a:active::after {
  background: blue;
  transition: background 0s;
}
<a href="javascript:void(0)"><span>Test link</span></a>

只使用一个伪元素:

a {
  display: inline-block;
  padding: 20px;
  background: #eeeeee;
  color: black;
  text-decoration: none;
  transition: background 1s;
  position: relative;
}

a span {
  position: relative;
  z-index: 1;
}

a:before {
  content: "";
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: transparent;
  z-index: 0;
  transition: background 1s;
}

a:hover {
  background: red;
  transition: background 0s;
}

a:active::before {
  background: blue;
  transition: background 0s;
}
<a href="javascript:void(0)"><span>Test link</span></a>

关于html - 在一个方向而不是另一个方向运行 CSS 过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48027631/

相关文章:

javascript - 如果选中复选框则显示/隐藏 div

jquery - 如何在将 jquery 与 css 一起使用后重置悬停功能

html - 尝试将 CSS 文件添加到 HTML 但出现 404 错误

javascript - HTML slider 不会隐藏

html - iframe 大小根据图像

css - 使用 CSS 将两个 UL 对齐到相同的基线

css - 响应式 CSS3 链式动画、暂停和恢复问题

firefox - 如何为所有属性指定 CSS3 过渡,但有一个异常(exception)/覆盖?

javascript - 将过渡效果应用于滑动内容

javascript - JQuery/CSS 触发动画