CSS:我可以轻松过渡到图像颜色变化悬停效果吗?

时间:2015-07-30 23:47:08

标签: css hover transition opacity easing

我创建了一个简单的效果,可以让图像在悬停时改变颜色。现在我想添加transition-timing-function属性,以便颜色过渡淡入淡出而不是瞬间变化,但我似乎无法让它工作。有什么想法吗?

以下是代码:

div {
  position: relative;
  display: inline-block;
  -webkit-transition: all 500ms ease-out 1s;
  -moz-transition: all 500ms ease-out 1s;
  -o-transition: all 500ms ease-out 1s;
  transition: all 500ms ease-out 1s;
}
img {
  width: 100%;
  height: 100%;
}
  div:hover::after {
  position: absolute;
  z-index: 1;
  background-color: Indigo;
  opacity: 0.4;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  content: '';

谢谢!

2 个答案:

答案 0 :(得分:0)

您的代码存在两个问题:

  1. ::after选择器作为单独的元素工作,因此div上的转换无效,它们需要应用于::after
  2. :hover::after选择器需要从过渡
  3. 这应该有效:

    div {
      position: relative;
      display: inline-block;
    }
    img {
      width: 100%;
      height: 100%;
    }
    div::after {
      -ms-transition: all 500ms ease-out 1s;
      transition: all 500ms ease-out 1s;
      position: absolute;
      z-index: 1;
      background-color: transparent;
      opacity: 0.4;
      left: 0;
      top: 0;
      height: 100%;
      width: 100%;
      content: '';
    }
    div:hover::after {
      background-color: Indigo;
    }
    

答案 1 :(得分:0)

有人还与我分享了这段代码,它似乎通过将图像包装在span类中来做同样的事情:

.imghov {
  display: inline-block;
  background-color: #fff;
  -moz-transition: all 0.3s linear;
  -ms-transition: all 0.3s linear;
  -o-transition: all 0.3s linear;
  -webkit-transition: all 0.13ss linear;
  transition: all 0.3s linear;
}

.imghov img {
  opacity: 1;
  -moz-transition: all 0.3s linear;
  -ms-transition: all 0.3s linear;
  -o-transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
  transition: all 0.3s linear;
}

.imghov:hover {
  background-color: indigo;
  -moz-transition: all 0.3s linear;
  -ms-transition: all 0.3s linear;
  -o-transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
  transition: all 0.3s linear;
}

imghov:hover,
.imghov:hover img {
  opacity: 0.6;
  -moz-transition: all 0.3s linear;
  -ms-transition: all 0.3s linear;
  -o-transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
  transition: all 0.3s linear;
}