原生js实现简单的倒计时

时间:2023-01-10 09:55:50

用原生实现了一个简单的倒计时,主要用到setInterval来控制时间100%至0%,当进度为0%时,clearInterval,然后在时间小于某个值时,小小改变了倒计时的填充颜色,当然了这只是一个雏形,可根据实际需要进行封装

附源码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .timeContainer{
            width: 200px;
            height: 30px;
            border-radius: 6px;
            border: 1px solid #ccc;
        }
        .timeContainer #countDown{
            height:100%;
            background: orange;
        }
    </style>
</head>
<body>倒计时:
    <div class="timeContainer">
        <div id="countDown" style="width: 100%;"></div>
    </div>
    <script type="text/javascript">
        window.onload = function () {
            myTime
        }
        function countDown () {
            let timeCount = document.getElementById('countDown')
            timeCount.style.width = parseInt(timeCount.style.width) - 1 + '%'
            if (timeCount.style.width < '30%') {
                timeCount.style.background = 'red'
            }
            if (timeCount.style.width == '0%') {
                window.clearInterval(myTime)
            }
        }
        let myTime = setInterval(function() {countDown()}, 100)
    </script>
</body>
</html>