JavaScript动画倒计时

问题描述 投票:0回答:1

我一直在尝试创建一个倒计时,使计数器每次变化时都会对文本进行动画处理。我可以在一开始就执行更改,但是不确定如何清除更改并重复执行。

HTML和CSS

<!DOCTYPE html>
<html>
<head>
    <!--meta http-equiv="refresh" content="4; url=index.php"-->
    <style type="text/css">
        p
        {
            transition: 1s;
            font-size: 100%;
        }
    </style>
</head>
<body>

<p>A script on this page starts this clock:</p>
<p id="demo">Login in....</p>

<script>

    //various javascript here

</script>
</body>
</html>

此脚本在第一次计数时更改一次CSS,但在计数2或1时不更改CSS。

//Set the counter variable
    var counter= 4;

    //Set the timer to count the counter down
    var timer = setInterval(function() 
    {
        counter--;
        if(counter== 0) 
        {
            clearInterval(timer);
        } 
        else 
        {
            //Execute the CSS change function
            styleChange();
        }
    }, 1000);

    function styleChange()
    {
        document.getElementById("demo").innerHTML = (counter);
        document.getElementById("demo").style.fontSize = "500%";
        document.getElementById("demo").style.opacity = "0";
        // In CSS "Demo" is given a transition of 1s to smooth out the animation"
    }

下一个脚本不会在每次计数器时重置样式,而是在样式之间切换,而不是我要尝试的样式,但至少重复一次,这与第一个脚本不同。它只会影响样式,如果可以的话,我会添加计时器。

    var myVar = setInterval(setStyle, 1000);

    function setStyle() {
      var x = document.getElementById("demo");
      x.style.fontSize = x.style.fontSize == "100%" ? "500%" : "100%";
    }

    function stopStyle() {
      clearInterval(myVar);
    }

我曾想过使用“ for”来遍历计数器的值,更改值的样式,然后再重新设置值,但我无法使其正常工作。视觉上效果应该像这样,但是要反向播放,而不要在酸-> https://www.youtube.com/watch?v=hsUKu9_Lr6U上播放。我从w3schools页面上大量借用了setInterval和clearInterval。

javascript css animation setinterval countdown
1个回答
1
投票

您不需要两个单独的间隔来使文本变大和变小。

相反,您可以使用CSS过渡将font-size从小到大进行动画处理,并使用2个嵌套的Window.requestAnimationFrame()调用来正确计时,如下所示:

const counter = document.getElementById('counter');

let value = 10;

const intervalID = setInterval(() => {
  if (value-- === 0) {
    clearInterval(intervalID);
    
    return;
  }
  
  requestAnimationFrame(() => {
    // Update the value and remove the `big` class in the next frame, so that
    // the text becomes smaller again:
    counter.textContent = value;
    counter.classList.remove('big');
  
    requestAnimationFrame(() => {
      // One more frame after that (so that the element has time to be re-rendered
      // with the smaller font-size, add the `big` class again:
      counter.classList.add('big');
    });
  });
  
}, 1000);
body {
  margin: 0;
  display: flex;
  height: 100vh;
  justify-content: center;
  align-items: center;
  font-family: monospace;
}

#counter.big {
  font-size: 500%;
  transition: font-size linear 1s;
}
<div id="counter" class="big">10</div>
© www.soinside.com 2019 - 2024. All rights reserved.