实现文字跑马灯效果,首先用到 substring()截取 和 setInterval计时器 clearInterval()清除计时器
效果如下:
实现代码如下:
<!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>跑马灯效果</title>
<script src="https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/2.6.14/vue.min.js"
type="application/javascript"></script>
</head>
<body>
<div id="app">
<button @click="lang">开始</button>
<button @click="stop">结束</button>
<h1> {{pao}} </h1>
</div>
<script>
let vm = new Vue({
el: "#app",
data() {
return {
pao: '这是一个会跑的文字~~~~~~',
setInterval: null
}
},
methods: {
lang() {
//阻止lang再次执行
if (this.setInterval != null) return
// 使用substring截取字符串
this.setInterval = setInterval(() => {
console.log(this.pao);
//获取头一个 字符
let qian = this.pao.substring(0, 1)
//获取后面的所以字符
let hou = this.pao.substring(1)
//将获取到的字符拼接起来
this.pao = hou + qian
}, 300)
},
stop() {
clearInterval(this.setInterval)
//每次清除计时器是 将setInterval 重新赋值为 null
this.setInterval = null
}
}
})
</script>
</body>
</html>
以上是实现文字跑马灯效果,如有不足的地方,欢迎在评论区留言。
标签:Vue,setInterval,js,substring,跑马灯,null,pao From: https://www.cnblogs.com/shilaoli/p/17333233.html