使用javascript可以设置css动画的当前百分比

Use javascript in order to set the current percentage of a css animation

本文关键字:百分比 动画 css javascript 设置 使用      更新时间:2023-09-26

我使用css动画来表示一天的太阳周期(从早上6点到下午6点)。不幸的是,我还希望能够根据一天中的时间设置当前的百分比(例如,如果当前时间是上午12点,我希望将太阳放在动画的50%。

这是我的小提琴:http://jsfiddle.net/vyhjt6mu/3/

这是我的代码:

/* Chrome, Safari, Opera */
@-webkit-keyframes sunAnimation {
  0% {
    left: -100px;
    top: 30%;
  }
  25% {
    left: calc(25% - 25px);
    top: 20%;
  }
  50% {
    left: calc(50% - 40px);
    top: 10%;
  }
  75% {
    left: calc(75% + 25px);
    top: 20%;
  }
  100% {
    left: calc(100% + 100px);
    top: 30%;
  }
}
@keyframes sunAnimation {
  0% {
    left: -100px;
    top: 30%;
  }
  25% {
    left: calc(25% - 25px);
    top: 20%;
  }
  50% {
    left: calc(50% - 40px);
    top: 10%;
  }
  75% {
    left: calc(75% + 25px);
    top: 20%;
  }
  100% {
    left: calc(100% + 100px);
    top: 30%;
  }
}
.sun {
  width: 100px;
  height: 100px;
  position: absolute;
  animation-name: sunAnimation;
  animation-duration: 60s;
  animation-timing-function: linear;
  -webkit-animation-name: sunAnimation;
  /* Chrome, Safari, Opera */
  -webkit-animation-duration: 60s;
  /* Chrome, Safari, Opera */
  -webkit-animation-timing-function: linear;
  /* Chrome, Safari, Opera */
}

如何简单地设置css3动画的当前百分比?如果做这件事很复杂,那么有图书馆吗?

谢谢你的帮助。

这不是重复的,因为需求不同。

要回答您的实际问题:是的,您可以使用CSS变量和JS的组合来实现这一点。

$(function () {
	$(window).mousemove(function (e) {
  	var t =  (-1/$(window).width()*e.pageX);
  	document.documentElement.style.setProperty('--delay', t+'s');
  });
});
:root {
    --delay: 0;
}
.box {
  width: 20px;
  height: 20px;
  background-color: #ff6600;
  animation: move 1s;
  animation-play-state: paused;
  animation-delay: var(--delay);
}
@keyframes move {
  100% { 
    transform: translate(200px, 100px) scale(2) rotate(180deg);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
</div>

您可以指定负animation-delay属性。

示例:http://jsfiddle.net/vyhjt6mu/4/

在这个例子中,我设置了animation-delay: -30s,所以动画将从中间点开始


对于这个任务,你可以在CSS中设置24不同的类(每小时一个),就像一样

.h00 {
  animation-delay: 0s; 
  -webkit-animation-delay: 0s; 
}
.h01 {
  animation-delay: -2.5s; 
  -webkit-animation-delay: -2.5s; 
}
.h02 {
  animation-delay: -5s; 
  -webkit-animation-delay: -5s; 
}
...
.h22 {
  animation-delay: -55s; 
  -webkit-animation-delay: -55s; 
}
.h23 {
  animation-delay: -57.5s; 
  -webkit-animation-delay: -57.5s; 
}

其中每小时之间的延迟差为2.5秒(60s/24);然后,通过JS,通过getHours()方法获得当前小时数,并将正确的类名应用于元素