通过向上滑动动画转换背景颜色

时间:2013-12-23 22:12:19

标签: css css3 css-transitions

我试图通过使用CSS过渡来改变悬停时元素的背景颜色。我想通过从底部向上滚动来做到这一点。我可以淡化使用它的背景,但我希望它向上滑动:

-webkit-transition: background-color 0.5s linear;
-moz-transition: background-color 0.5s linear;
-o-transition: background-color 0.5s linear;  
transition: background-color 0.5s linear;

另一个想法是,在应用背景的情况下向上滚动一个单独的元素会更好吗?

2 个答案:

答案 0 :(得分:69)

为了向上滑动背景颜色,您需要使用背景图片或某种渐变,同时逐步调整background-position

.box {
    width: 200px; height: 100px;
    background-size: 100% 200%;
    background-image: linear-gradient(to bottom, red 50%, black 50%);
    transition: background-position 1s;
}

.box:hover {
    background-position: 0 -100%;
}

您可以在此处查看此演示:http://jsfiddle.net/as5ZU/

答案 1 :(得分:2)

@Sampson答案的扩展,在这里我认为更容易理解的友好值:

.box {
  width: 100px;
  height: 100px;
  display:inline-block;
  background-size: 200% 200%;
  transition: background-position 1s;
}

.to-top{
  background-image: linear-gradient(to top, red 50%, black 0);
  background-position: top;
}

.to-top:hover {
  background-position: bottom;
}

.to-bottom{
  background-image: linear-gradient(to bottom, red 50%, black 0);
  background-position: bottom;
}

.to-bottom:hover {
  background-position: top;
}

.to-left{
  background-image: linear-gradient(to left, red 50%, black 0);
  background-position: left;
}

.to-left:hover {
  background-position: right;
}

.to-right{
  background-image: linear-gradient(to right, red 50%, black 0);
  background-position: right;
}

.to-right:hover {
  background-position: left;
}
<div class="box to-top"></div>

<div class="box to-bottom"></div>

<div class="box to-left"></div>

<div class="box to-right"></div>

这里有更多花哨的过渡:

.box {
  width: 100px;
  height: 100px;
  display:inline-block;
  transition:  1s;
}

.to-center{
  background: 
    linear-gradient(black,black) no-repeat,
    red;
  background-size: 100% 100%;
  background-position:center;
}

.to-center:hover {
  background-size: 0% 100%; /* Or 100% 0% */
}

.from-center{
  background: 
    linear-gradient(red,red) no-repeat,
    black;
  background-size: 0% 100%;  /* Or 100% 0% */
  background-position:center;
}

.from-center:hover {
  background-size: 100% 100%;
}

.diagonal-right{
  background-image:linear-gradient(to bottom right,red 49.5%,black 50%);
  background-size: 200% 200%;
  background-position:bottom right;
}

.diagonal-right:hover {
  background-position:top left;
}

.diagonal-left{
  background-image:linear-gradient(to bottom left,red 49.5%,black 50%);
  background-size: 200% 200%;
  background-position:bottom left;
}

.diagonal-left:hover {
  background-position:top right;
}
<div class="box to-center"></div>

<div class="box from-center"></div>

<div class="box diagonal-right"></div>


<div class="box diagonal-left"></div>

相关问题以获取有关background-positionbackground-size结合使用的工作方式的更多详细信息:Using percentage values with background-position on a linear gradient