Vue3实现跑马灯效果
本文实例为大家分享了Vue3实现跑马灯效果的具体代码,供大家参考,具体内容如下
先看效果:
html部分代码
<div class="app"> <p :class="{tabcolor:color}">{{str}}</p> <button @click="play">开始</button> <button @click="stop">停止</button> </div>
注意: :class="{tabcolor:color}" 是给<p></p>标签内的文字加上一个颜色,当我们点击开始按钮的时候。
CSS部分代码
.tabcolor { color: cornflowerblue; }
CSS部分的代码很简单,就是给了一个添加颜色的类。
Vue部分代码
Vue.createApp({ data() { return { str: "你好啊,我是稳重聪头~", id: null, color: false, } }, methods: { play() { clearInterval(this.id); this.color = !this.color; this.id = setInterval(() => { this.str = this.str.slice(1) + this.str.slice(0, 1) }, 800) }, stop() { clearInterval(this.id); this.color = false; } } }).mount(".app")
分析:
1、data上定义一个字符串,这个字符串就是要在<p></p>标签里进行滚动的。
2、给开始和关闭按钮,绑定事件:v-on; @cliick就是v-on的简写。
3、在按钮的事件函数中,写相关的业务逻辑代码:拿到str字符串,然后 调用字符串 slice 来进行字符串的截取操作,把第一个字符截取出来,放到最后一个位置即可。
4、为了实现最终结果,自动截取的功能,需要把步骤三的代码放到一个定时器中去。
最后在送上完整代码
<!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="./js/vue.js"></script> <style type="text/css"> .tabcolor { color: cornflowerblue; } </style> </head> <body> <div class="app"> <p :class="{tabcolor:color}">{{str}}</p> <button @click="play">开始</button> <button @click="stop">停止</button> </div> </body> <script> Vue.createApp({ data() { return { str: "你好啊,我是稳重聪头~", id: null, color: false, } }, methods: { play() { clearInterval(this.id); this.color = !this.color; this.id = setInterval(() => { this.str = this.str.slice(1) + this.str.slice(0, 1) }, 800) }, stop() { clearInterval(this.id); this.color = false; } } }).mount(".app") </script> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Vue 中指令v-bind动态绑定及与v-for结合使用详解
这篇文章主要为大家介绍了Vue 中指令v-bind动态绑定及与v-for结合使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-09-09axios封装,使用拦截器统一处理接口,超详细的教程(推荐)
这篇文章主要介绍了axios封装使用拦截器处理接口,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-05-05
最新评论