朋友的項目里要實現一個消息無縫滾動的效果,中途遇到了一點小bug,每組消息滾動完再次循環時會出現停留兩倍的時間間隔問題,我研究了一天終于解決了這個1S的小問題
項目環境vue-cli ,請自行配置好相應的,環境及路由,這里主要介紹實現的方法
第一步在模板中 使用v-for方法循環出消息列表
<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>以上就是這篇文章的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答