我使用css动画来表示一天的太阳周期(从早上6点到晚上6点)。 不幸的是,我还希望能够根据一天中的时间设置当前百分比(例如,如果当前时间是上午12点,我想将太阳置于动画的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 */
}
如何设置css3动画的当前百分比?如果这样做非常复杂,那么存在一个库吗?
感谢您的帮助。
这不是重复,因为需求不同。
答案 0 :(得分:4)
您可以指定负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()
方法获取当前小时,并将正确的类名应用于元素
答案 1 :(得分:0)
要回答您的实际问题: 是的,您可以同时使用CSS-vars和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>