使用javascript设置css动画的当前百分比 [英] Use javascript in order to set the current percentage of a css animation

查看:521
本文介绍了使用javascript设置css动画的当前百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use a css animation to represent the sun cycle for a day (from 6AM to 6PM). Unfortunatly, I want also to be able to set the current percentage depending on the time of the day (for example, if the current time is 12AM, I want to put the sun at 50% of the animation.

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

Here is my 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 */
}

我该怎么办?只需设置css3动画的当前百分比?如果这样做非常复杂,那么存在一个库吗?

How can I simply set the current percentage of a css3 animation ? If it's very complex to do it, does a library exist for that ?

感谢您的帮助。

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

It's not a duplicate because the needs are different.

推荐答案

您可以指定负动画延迟属性。

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

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

In that example I've set animation-delay: -30s so the animation will start from the middle point

对于此任务,您可以设置 24 CSS中的不同类(每小时一个),如此

For this task you could set 24 different classes in CSS (one for each hour) like so

.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()方法获取当前小时,并将正确的类名应用于元素

where the difference of delay between each hour is 2.5 seconds (60s/24); then, via JS, get the current hour via getHours() method and apply the right class name to your element

这篇关于使用javascript设置css动画的当前百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆