padStart()补零(附倒计时案例)

padStart()

这个是字符串提供的方法,所以我们先要保证调用的地方是个字符串

这个方法里两个参数

.padStart(显示的位数,位数不足时在前面补充的内容)

例:
.padStart(2,0)不足两位时在前面补零

padEnd()

和上面用法一样,这个是在后面补一个值

附倒计时案例

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        input {
            width: 14px;
        }
    </style>
</head>

<body>
    <div id='app'>
        <input type="text" v-model:value='sec' disabled>:<input type="text" v-model:value='msec' disabled>
        <br>
        <button @click="start" :disabled=flag>开始</button>
        <button @click="stop" :disabled=!flag>停止</button>
    </div>
</body>
<script>
    const vm = new Vue({
        el: "#app",
        data: {
            num: 1000,
            sec: '10',
            msec: '00',
            flag: false
        },
        methods: {
            start() {
                this.flag = true;
                sec = 0;
                this.timer = setInterval(() => {
                    this.num--;
                    // 补零
                    this.sec = (String(Math.floor(this.num / 100))).padStart(2,0);
                    this.msec = (String(this.num).substring(String(this.num).length - 2)).padStart(2, 0);
                    if (this.num == 0) {
                        clearInterval(this.timer);
                        this.num = 1000;
                    }
                }, 10);
            },
            stop() {
                clearInterval(this.timer);
                this.flag = false;
            }
        },
    });
</script>

</html>

 

posted @ 2021-09-14 21:40  从入门到入土  阅读(299)  评论(0编辑  收藏  举报