vue实现每隔一段时间改变颜色

本文介绍如何在 Vue.js 应用中使用 JavaScript 实现组件颜色的定时切换,通过定时器更新数据绑定,实现动态视觉效果。
<!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">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <title>字体随机变色</title>
    <style>
        div {
            transition: all 0.5s;
            font-weight: bold;
            font-size: 30px;
        }
    </style>
</head>

<body>
    <div id="app">
        <p :style="{'color':pColor}">变换颜色的文本</p>
    </div>
    <!-- 16种颜色随机变化 每一秒钟变化一次 -->

</body>
<script>
    new Vue({
        el: '#app',
        data() {

            return {
                timer: null, //定时器名称\n  
                color: ['#f00', '#000', 'yellow', 'blue', 'black', 'gold', 'orange', 'gray', 'pink', 'maroon',
                    'green', 'rgb(42, 75, 165)', '#009393', '#bbffbb', '#ceceff', 'purple'
                ],
                pColor: '',
            }
        },
        created() {
            this.setTime();
        },
        beforeDestroy() {
            clearInterval(this.timer); // 清除定时器\n  
            this.timer = null;
        },
        methods: {
            setTime() {
                //每隔一分钟运行一次保存方法\n
                this.timer = setInterval(() => {
                    this.saveList();
                }, 1000)
            },
            saveList() {
                var math = Math.floor(Math.random() * this.color.length); // 获取随机数
                this.pColor = this.color[math]; //替换字体颜色

            }
        }

    })
    
</script>

</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值