簡體   English   中英

如何使用JavaScript禁用CSS轉換,更新樣式,然后快速恢復轉換

[英]How to disable CSS transitions, update styles, and then restore transitions quickly with JavaScript

我正在構建一個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類。 這應該平滑過渡,因為旋轉從-96deg變為-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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM