先上效果图,解释都在代码注释里边
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document </title> </head> <body> <div id="app"> <input type="button" value="帅起来" @click=‘shuai‘> <input type="button" value="歇会儿" @click=‘stop‘> <div>{{ msg }}</div> </div> <script src="https://unpkg.com/[email protected]/dist/vue.js"></script> <script> var vm = new Vue({ el: ‘#app‘, data: { msg: ‘屏幕前的你,很帅~~~‘, intervalId: null //在data上定义 定时器ID }, methods: { shuai() { // 开启跑动 if (this.intervalId != null) return//设置一个锁,防止开启多个定时器 this.intervalId = setInterval(() => { let start = this.msg.substring(0, 1)//获取到头的第一个字符 let end = this.msg.substring(1)//获取到 后面的所有字符 this.msg = end + start //重新拼接得到新的字符串并赋值给this.msg }, 400) }, stop() { //停止定时器 clearInterval(this.intervalId)//清理定时期 this.intervalId = null//再把this.intervalId设置为null(暂停后可以再次开启跑动) } } }) </script> </body> </html>
原文地址:https://www.cnblogs.com/yangpeixian/p/11697897.html
时间: 2024-10-10 13:52:40