1. 程式人生 > >微信小程式文字跑馬燈效果

微信小程式文字跑馬燈效果

WXML

<scroll-view class="container">
  <view class="scrolltxt">
    <view class="marquee_box">
      <view class="marquee_text" style="transform: translateX(-{{marqueeDistance}}px)">
        <text>{{text}}</text>
        <text style="margin-right:{{marquee_margin}}px;"></text>
        <text style="margin-right:{{marquee_margin}}px;">{{text}}</text>        
      </view>
    </view>
  </view>
</scroll-view>

WXSS

.container {display: flex;flex-direction: column;justify-content: space-between;box-sizing: border-box;}
.scrolltxt{padding:0 20rpx;background:#f8f8f8;}
.marquee_box {position:relative;color:#333;height:90rpx;display:block;overflow:hidden;} 
.marquee_text {white-space: nowrap;position:absolute;top:0;font-size:14px;height:90rpx;line-height:90rpx;}

JS

  data: {
    //滾動字幕
    text: "溫馨提示:為了保證其他購買者的利益,每個 賬號針對同一商品只允許退款一次,請您謹慎操作。",
    marqueePace: 1,//滾動速度
    marqueeDistance: 0,//初始滾動距離
    marquee_margin: 30,//間距
    size: 14,//字號
   time: '',// 定時器
  },

onHide: function () {
    //清空滾動字幕定時器,避免鎖屏或頁面隱藏後移動速度越來越快
    clearInterval(this.data.time);
  },

  onShow: function (e) {
    var that = this;
    var length = that.data.text.length * that.data.size;//文字長度
    var windowWidth = wx.getSystemInfoSync().windowWidth;// 螢幕寬度
    //console.log(length,windowWidth);
    that.setData({
      length: length,
      windowWidth: windowWidth
    });
    that.scrolltxt();// 第一個字消失後立即從右邊出現
  },

 /**
   * 滾動字幕
   */
  scrolltxt: function () {
    var that = this;
    var length = that.data.length;//滾動文字的寬度
    var windowWidth = that.data.windowWidth;//螢幕寬度
    var time = this.data.time
    if (length > windowWidth) {
      time = setInterval(function () {
        var maxscrollwidth = length + that.data.marquee_margin;//滾動的最大寬度,文字寬度+間距,如果需要一行文字滾完後再顯示第二行可以修改marquee_margin值等於windowWidth即可
        var crentleft = that.data.marqueeDistance;
        if (crentleft < maxscrollwidth) {//判斷是否滾動到最大寬度
          that.setData({
            marqueeDistance: crentleft + that.data.marqueePace
          })
        }
        else {
          that.setData({
            marqueeDistance: 0 // 直接重新滾動
          });
          clearInterval(time);
          that.scrolltxt();
        }
      }, 20);
    }
    else {
      that.setData({ marquee_margin: "1000" });//只顯示一條不滾動右邊間距加大,防止重複顯示
    }
    that.setData({
      time:time
    })
  },