美文网首页
2019-05-31指令的综合运用之跑马灯效果

2019-05-31指令的综合运用之跑马灯效果

作者: 啊_6424 | 来源:发表于2019-05-31 23:28 被阅读0次

先写出来一个页面:

<!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>跑马灯效果</title>
  <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<style>
  .text{
    padding-top:20px;
  }
  [v-cloak]{
    display: none;
  }
</style>
<body>
  <div id="app">
    <input type="button" :value="action1" @click="move"><input type="button" :value="action2" @click="stop">
    <div class="text" v-cloak>{{msg}}</div>
  </div>
</body>
</html>
<script>
  var vm = new Vue({
    el:"#app",
    data:{
      msg:" 六界第一美女:就是偶~~~",
      action1:"动起来",
      action2:"停止"
    },
    methods:{
      move:function(){

      },
      stop:function(){

      }
    }
  })
</script>
页面布局好了

再实现动态的事件

要求:

点击动起来就截取字符串第一个文字并添加到最后一个

用函数截取第一个字符串,再函数拼接,再显示到页面上

点击停止则停止截取字符串

设置一个boolean的move,为true时表示动起来了,为false表示停止了

点击动起来后会一直不停的截取直到点击停止

考虑用一个计时器实现,每隔多少时间截取一次

最后js代码如下
<script>
  var vm = new Vue({
    el:"#app",
    data:{
      msg:"六界第一美女:就是偶~~~",
      action1:"动起来",
      action2:"停止",
      timer: null
    },
    methods:{
      move:function(){
        //var _this = this;//注意这里有个this指向问题,用箭头函数后可以不用这一步
       this.timer = setInterval(() => {
          var head =  this.msg.substring(0,1);
          var tail = this.msg.substring(1);
          this.msg = tail+ head;
        },400)
      },
      stop:function(){
        clearInterval(this.timer);
      }
    }
  })
</script>

我写的js代码问题:

点击一下动起来就创建一个timer,当用户点击多下动起来时页面中就有多个timer,速度加快了的bug。

改正后的js代码
<script>
  var vm = new Vue({
    el:"#app",
    data:{
      msg:"六界第一美女:就是偶~~~",
      action1:"动起来",
      action2:"停止",
      timer: null
    },
    methods:{
      move:function(){
        //var _this = this;//注意这里有个this指向问题,用箭头函数后可以不用这一步
        if(this.timer !== null){return;}
        this.timer = setInterval(() => {
          var head =  this.msg.substring(0,1);
          var tail = this.msg.substring(1);
          this.msg = tail+ head;
        },400)
      },
      stop:function(){
        clearInterval(this.timer);//这里虽然清除了定时器,但定时器并没有为null
        console.log(this.timer);//测试时,输出的是整型的数字
        this.timer = null;
      }
    }
  })
</script>

相关文章

网友评论

      本文标题:2019-05-31指令的综合运用之跑马灯效果

      本文链接:https://www.haomeiwen.com/subject/miuntctx.html