向元素线性渐变度添加动画

时间:2019-04-26 22:09:42

标签: jquery css3 linear-gradients

我正在制作这个演示。如何基于.box#anim-left点击,向带有动画的#anim-right线性渐变 增减90度?

我能够添加一些CSS,但这正在改变程度

$("#anim-left").on("click", function() {
  $('.box').toggleClass('box-reverse');

  // setInterval(function(){ }, 1);

  //    $(this).css({
  //     background: "linear-gradient(90"+90+"deg, #fff 50%, #ffe600 50%)" 
  // });

});

$("#anim-right").on("click", function() {
  $('.box').toggleClass('box-reverse');

  // setInterval(function(){ }, 1);

  //    $(this).css({
  //     background: "linear-gradient(90"+90+"deg, #fff 50%, #ffe600 50%)" 
  // });

});
.box {
  height: 120px;
  width: 120px;
  background: linear-gradient(90deg, red 50%, blue 50%);
  transition: all 3s ease-in-out;
}

.box-reverse {
  background: linear-gradient(270deg, red 50%, blue 50%);
  transition: all 3s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>

<button id="anim-left"> Animate To Left </button>
<button id="anim-right"> Animate To Right </button>

1 个答案:

答案 0 :(得分:1)

您无法为渐变设置动画,但在这种情况下,您可以考虑进行简单的旋转:

import static org.mockito.ArgumentMatchers.any
import static org.mockito.Mockito.when
$("#anim-left").on("click", function() {
  $('.box').toggleClass('box-reverse');

});

$("#anim-right").on("click", function() {
  $('.box').toggleClass('box-reverse');
});
.box {
  height: 120px;
  width: 120px;
  position:relative;
  overflow:hidden;
}
.box:before {
  content:"";
  top:-25px;
  left:-25px;
  right:-25px;
  bottom:-25px;
  position:absolute;
  background: linear-gradient(90deg, red 50%, blue 50%);
  transition: all 3s ease-in-out;

}

.box-reverse:before {
  transform:rotate(180deg);
}

如果要连续播放动画,只需考虑增加/减少的变量即可:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>

<button id="anim-left"> Animate To Left </button>
<button id="anim-right"> Animate To Right </button>
var rotation = 0;

$("#anim-left").on("click", function() {
  rotation -= 90;
  $('.box').css("--r", rotation + "deg");

});

$("#anim-right").on("click", function() {
  rotation += 90;
  $('.box').css("--r", rotation + "deg");
});
.box {
  height: 120px;
  width: 120px;
  position: relative;
  overflow: hidden;
}

.box:before {
  content: "";
  top: -25px;
  left: -25px;
  right: -25px;
  bottom: -25px;
  position: absolute;
  background: linear-gradient(90deg, red 50%, blue 50%);
  transform: rotate(var(--r, 0deg));
  transition: all 1s ease-in-out;
}