添加/删除类时,动画背景颜色向下滑动,仅使用CSS?

时间:2018-02-10 16:02:59

标签: css css3 animation css-animations

你好我需要动画更改div的背景,新背景从上面向下滑动。

This is an example of what I can do now and the context of my question.

我需要通过添加和删除类来触发动画:

.token {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  border-radius: 50%;
  margin-bottom: 20px;
  transition: background 1000ms linear;
}

.red {
  background: red;
}

.blue {
  background: blue;
}

正如你所看到的,我已经放了一个小动画,但我不确定单独使用CSS是否可以实现下滑效果。

我想要的是能够创建多个类,每个类通过向下滑动来改变它们应用于div的背景。

我需要通过添加一个类来触发动画,该类应该包含要转换的颜色。

1 个答案:

答案 0 :(得分:1)

您可以对颜色使用线性渐变,您可以通过调整background-size来创建效果。

这是一个想法:

let previousClass="";
function color(className) {
  $('#token').removeClass(previousClass);
  previousClass=className;
  setTimeout(function() {
      $('#token').addClass(previousClass);
  }, 500);

}
.token {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  border-radius: 50%;
  margin-bottom: 20px;
  background-size: 100% 0;
  background-position: 0 0;
  background-repeat: no-repeat;
  background-image: linear-gradient(white, white);
  transition: 0.5s background-size linear;
}

.red {
  background-image: linear-gradient(red, red);
  background-size: 100% 100%;
}

.blue {
  background-image: linear-gradient(blue, blue);
  background-size: 100% 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="token" id="token"></div>
<button onclick="color('red')">Red</button>
<button onclick="color('blue')">Blue</button>

相关问题