VUE繫結事件案例—文字跑馬燈效果
阿新 • • 發佈:2021-01-29
技術標籤:vue
VUE繫結事件案例—文字跑馬燈效果
要實現的效果:點選【浪起來】的時候,文字逐漸向左移動一個單位(迴圈);
點選【猥瑣發育】,文字停止移動。
程式碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文字跑馬燈</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="浪起來" @click="lang">
<input type ="button" value="猥瑣發育" @click="stop">
<h4> {{mess}} </h4>
</div>
</body>
<script>
var vm = new Vue({
el: "#app",
data: {
mess: "猥瑣發育,別浪!!!",
timer:""
} ,
methods: {
lang() {
if(this.timer!="") return; //每次被點選了,就清除定時器,避免多次點選,越跑越快
this.timer = setInterval(() => {
const start = this.mess.substring(0, 1)//獲取到第一個字元
const end = this.mess.substring(1)//獲取到第一個後面的字元
this.mess = end + start//重新組成新的資料
}, 300)
},
stop() {
clearInterval(this.timer);
this.timer="" //每次清除了定時器,就讓定時器重新賦值為空
}
}
})
</script>
</html>