我正在 css 和 javascript 的帮助下开发一个虚拟时钟。随着时间的流逝,我使用了以下变换来变换时钟的指针。我的问题是,当手臂到达一小时结束时,即从第 59 个滴答声过渡到第 1 个滴答声时,它会很快地将手臂卷回到一小时的开始,而不是保持其路线。换句话说,在第 59 个刻度时,它会执行 -59,而不是加 1 并重置计数器。
function setDate(){
const now = new Date();const seconds = now.getSeconds();
const secondsDegrees = ((seconds/60) * 360) + 90;
secondHand.style.transform = `rotate(${secondsDegrees}deg)`;
const minutes = now.getMinutes();
const minutesDegrees = ((minutes/60) * 360) +90;
minuteHand.style.transform = `rotate(${minutesDegrees}deg)`;
const hours = now.getHours();
const hoursDegrees = ((hours/12) * 360) +90;
hourHand.style.transform = `rotate(${hoursDegrees}deg)`;
}
我尝试通过添加 if...else 语句来禁用最后一秒的过渡效果来解决该问题。这对输出没有任何影响。我认为当我打开和关闭动画时,倒回动画会更快。
if (seconds == 0) {
transition = false;
if(seconds > 0){
transition = true;
} else {
transition = false;
}}
尝试每次检查秒/分钟/小时值,检查 X 过去时间的绝对值。 然后你不会在 60 后重置为 0,而是继续到 61、62 等,动画看起来会继续。
const hours = document.getElementById('hours');
const minutes = document.getElementById('minutes');
const seconds = document.getElementById('seconds');
function setDate(){
const time = new Date().getTime() / 1000 % (60 * 60 * 12 * 10);
const secondsDegrees = Math.floor(time) / 60 * 360 - 90;
seconds.style.setProperty('--rotate', secondsDegrees+'deg');
const minutesDegrees = Math.floor(time / 60) / 60 * 360 -90;
minutes.style.setProperty('--rotate', minutesDegrees+'deg');
const hoursDegrees = (Math.floor(time/60/60) - new Date().getTimezoneOffset()/60) / 12 * 360 -90;
hours.style.setProperty('--rotate', hoursDegrees+'deg');
}
setDate();
setInterval(setDate, 1000);
#clock {
width: 100px;
height: 100px;
border-radius: 50%;
border: 2px solid black;
margin: 10px;
position: relative;
}
#hours, #minutes, #seconds {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-2px, -50%) rotate(var(--rotate, 0));
transform-origin: 2px 50%;
border-radius: 4px;
transition: transform .2s ease;
}
#hours {
width: 30px;
height: 6px;
background: black;
}
#minutes {
width: 45px;
height: 4px;
background: #414141;
}
#seconds {
width: 45px;
height: 2px;
background: #fa48a1;
}
<div id="clock">
<div id="hours"></div>
<div id="minutes"></div>
<div id="seconds"></div>
</div>