溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

vue實現消息的無縫滾動效果的示例代碼

發(fā)布時間:2020-09-04 17:00:14 來源:腳本之家 閱讀:253 作者:candy 欄目:web開發(fā)

朋友的項目里要實現一個消息無縫滾動的效果,中途遇到了一點小bug,每組消息滾動完再次循環(huán)時會出現停留兩倍的時間間隔問題,我研究了一天終于解決了這個1S的小問題

項目環(huán)境vue-cli ,請自行配置好相應的,環(huán)境及路由,這里主要介紹實現的方法

第一步在模板中 使用v-for方法循環(huán)出消息列表

<template>

<div id="box">
  <ul id="con1" ref="con1" :class="{anim:animate==true}">
    <li v-for='item in items'>{{item.name}}</li>
  </ul>
</div>
</template>

第二步在<script>標簽中放置消息數組和具體的method 方法。

<script>

 export default {
data() {
 return {
   animate:false,
   items:[  //消息列表對應的數組
     {name:"馬云"},
     {name:"雷軍"},
     {name:"王勤"}
   ]
 }
},
created(){
  setInterval(this.scroll,1000) // 在鉤子函數中調用我在method 里面寫的scroll()方法,注意此處不要忘記加this,我在這個位置掉了好幾次坑,都是因為忘記寫this。
},
methods: {
  scroll(){
    let con1 = this.$refs.con1;
    con1.style.marginTop='-30px';
    this.animate=!this.animate;
    var that = this; // 在異步函數中會出現this的偏移問題,此處一定要先保存好this的指向
    setTimeout(function(){
        that.items.push(that.items[0]);
        that.items.shift();
        con1.style.marginTop='0px';
        that.animate=!that.animate;  // 這個地方如果不把animate 取反會出現消息回滾的現象,此時把ul 元素的過渡屬性取消掉就可以完美實現無縫滾動的效果了
    },500)
  }
}
}
</script>

<style>

*{
  margin: 0 ;
  padding: 0;
}
#box{
  width: 300px;
  height: 32px;
  line-height: 30px;
  overflow: hidden;
  padding-left: 30px;
  border: 1px solid black;
  transition: all 0.5s;
}
.anim{
  transition: all 0.5s;
}
#con1 li{
  list-style: none;
  line-height: 30px;
  height: 30px;
}
</style>

以上就是這篇文章的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI