如何用js实现可随意控制的进度条

2021-01-12  本文已影响0人  plum_meizi

1.用div画出loading样式


GIF 2021-1-13 12-19-46.gif
<div class="play-video" v-if="showPlayLoading">
    <div class="play-loading">
        <div :style="{ width: `${progressWidth / 100}rem` }" class="play-loading-in"></div>
    </div>
</div>
image.png

红框内的div用背景色填充,然后用js控制其长度,就可实现loading

2.用js控制loading层里面的长度

private playLoading(bool) {
    console.log('是否显示动画', bool);
    // 先清除一下定时器
    if (this.playtimer1) {
        clearInterval(this.playtimer1);
        this.playtimer1 = null;
    }
    if (this.playtimer2) {
        clearInterval(this.playtimer2);
        this.playtimer2 = null;
    }

    // 展示loading,刚开始按照1s加载10%的速度进行,加载到90%停止
    this.showPlayLoading = true;
    if (bool) {
        this.$nextTick(() => {
            this.playtimer1 = window.setInterval(() => {
                if (this.progressWidth > 412 * 0.9) {
                    if (this.playtimer1) {
                        clearInterval(this.playtimer1);
                        this.playtimer1 = null;
                    }
                }
                this.progressWidth += 2.06;
            }, 50);
        });
    } else {
        // 如果资源加载完毕,直接加快速度到终点,并隐藏
        this.playtimer2 = window.setInterval(() => {
            if (this.progressWidth > 412 - 8.24) {
                this.showPlayLoading = false;
                if (this.playtimer2) {
                    clearInterval(this.playtimer2);
                    this.playtimer2 = null;
                    this.progressWidth = 123.6;
                }
            }
            this.progressWidth += 4.12;
        }, 10);
    }
}

如果是固定时间的loading动画,可以用animation动画来做,但是想要资源加载完成就快速跑完,动画的中途,根本不知道进度条加载到哪里了,就无法做到继续之前的长度加载,所以要用js来控制width,用width++,就可以搞定

上一篇 下一篇

猜你喜欢

热点阅读