使用javascript为了设置css动画的当前百分比

I_A*_*oto 5 javascript animation css3

我使用css动画表示一天的太阳周期(从6AM到6PM)。不幸的是,我还希望能够根据一天中的时间设置当前百分比(例如,如果当前时间为12AM,我希望将太阳置于动画的50%处。

这是我的jsfiddle: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 */
}
Run Code Online (Sandbox Code Playgroud)

如何简单地设置CSS3动画的当前百分比?如果执行起来非常复杂,那么是否存在为此提供的库?

谢谢你的帮助。

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

小智 8

回答您的实际问题:是的,您可以使用 CSS-vars 和 JS 的组合来实现此目的。

$(function () {

	$(window).mousemove(function (e) {
  	var t =  (-1/$(window).width()*e.pageX);
  	document.documentElement.style.setProperty('--delay', t+'s');
  });
});
Run Code Online (Sandbox Code Playgroud)
: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);
  }
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
</div>
Run Code Online (Sandbox Code Playgroud)


fca*_*ran 5

您可以指定负属性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; 
}
Run Code Online (Sandbox Code Playgroud)

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