进度条如何实现在暂停后继续播放?

quasar的notify有个进度条功能,element的message会在鼠标移入移出时重新进行关闭计时
现在想把两者结合起来,即:

鼠标移入时关闭计时,进度条暂停播放动画。
鼠标移出时继续计时,进度条继续播放动画

目前遇到的问题是进度条如何继续播放,下面是简化后的代码:

<template>
    <el-row type="flex" style="width: 800px">
            <div class="el-message el-message--success" style="position: static;transform: translateX(0)">
                <i class="el-message__icon el-icon-success"/>
                <p class="el-message__content">成功提示</p>
                <div v-if="!closed" class="el-message__progress" :style="progressStyle"/>
            </div>
            <el-button type="primary" style="margin-left: 50px" @click="startTimer">播放</el-button>
            <el-button type="primary" @click="clearTimer">暂停</el-button>
        </el-row>
</template>

<script>
    export default {
        data() {
            return {
                duration: 3000,//多少毫秒后关闭
                startAt: 0,//上一次开始关闭计时的时间
                remainTime: 0,//还剩多少毫秒关闭
                pause: false,
                closed: false,
                timer: null
            }
        },
        computed: {
            progressStyle() {
                if (this.closed) return 'transform: scaleX(0)'
                if (this.pause) return `transform: scaleX(${this.remainTime / this.duration})`
                return `animation-duration: ${this.remainTime}ms`
            }
        },
        methods: {
            clearTimer() {
                this.pause = true
                this.remainTime -= Date.now() - this.startAt
                clearTimeout(this.timer)
            },
            startTimer() {
                this.pause = false
                this.startAt = Date.now()
                if (this.remainTime === 0) this.remainTime = this.duration
                this.timer = setTimeout(() => this.closed = true, this.remainTime)
            }
        },
        mounted() {
            this.startTimer()
        }
    }
</script>

<style lang="scss">
.el-message__progress {
        z-index: -1;
        position: absolute;
        height: 3px;
        bottom: 0;
        left: 10px;
        right: 10px;
        animation: el-message-progress linear;
        background: currentColor;
        opacity: .3;
        transform-origin: 0 50%;
        transform: scaleX(0);
    }
@keyframes el-message-progress {
    0% {
        transform: scaleX(1)
    }
    100% {
        transform: scaleX(0)
    }
}
</style>

有啥思路吗?

阅读 2k
1 个回答

首先看你动画是什么做的?你的方案是 animation-play-state: paused;

  1. js 实现,那么把定时器停了即可
  2. css 实现

    1. transition
    2. animation 使用 animation-play-state: paused;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题