gpt4 book ai didi

javascript - 如何禁用 CSS 过渡、更新样式,然后使用 JavaScript 快速恢复过渡

转载 作者:行者123 更新时间:2023-11-28 00:03:47 24 4
gpt4 key购买 nike

我正在构建一个 CSS 和 JavaScript 时钟,它使用 transform: rotate(xdeg) 来旋转时钟指针。 CSS transition 属性用于平滑每次指针旋转并模拟真实时钟。指针是 div,绝对位于 top: 50%left: 50% 开始,指向 12 点时旋转 -90 度。

所以秒针的完整周期是每秒增加 6 度,从 -90 度到 264 度,然后回到 -90 度。问题在于,应用于指针的转换会使指针在从 264 度到 -90 度(59 秒到 0 秒)时全天候倒退。

我已经尝试检查秒针何时位于 59 秒(transform: rotate(264deg)),通过设置 no-transition 暂时禁用转换元素上的类,将 transform 属性更改为 rotate(-96deg),这在外观方面与 rotate(264deg) 相同,然后删除 no-transition 类。这应该平滑过渡,因为旋转从 -96 度变为 -90 度。请参阅下面的代码。

JavaScript:

const secondsHand = document.querySelector('.seconds-hand');

function setTime(){
const now = new Date();
const seconds = now.getSeconds();

let secondsDegrees = ((seconds / 60) * 360) - 90;
secondsHand.style.transform = `rotate(${secondsDegrees}deg)`;

if(seconds === 59){
secondsDegrees = -96;
secondsHand.classList.add('no-transition');
secondsHand.style.transform = `rotate(${secondsDegrees})`;
secondsHand.classList.remove('no-transition');
}

// Code to handle other hands of the clock goes here

}

CSS:

.no-transition {
transition: none !important;
}

不幸的是,这不起作用。这是问题的代码笔:https://codepen.io/tillytoby/pen/axRByw

最佳答案

查看您的代码,我可以看到您添加了一个“无转换”类,然后将其删除。应该在'n'秒之前进行删除。您可以通过使用 setInterval 来实现。检查:

if(seconds === 59){
secondsDegrees = -96;
secondsHand.classList.add('no-transition');
secondsHand.style.transform = `rotate(${secondsDegrees}deg)`;
//1000 is the delay, in this case 1000 miliseconds.
setTimeout( function () {secondsHand.classList.remove('no-transition');},1000)
}

关于javascript - 如何禁用 CSS 过渡、更新样式,然后使用 JavaScript 快速恢复过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55836440/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com