小程序公告輪播(走馬燈效果)

使用Animation,setTimeval完成單行輪播
git文件地址
https://github.com/zhangrui-1...css

clipboard.png

wxml文件git

<view class='contain'>
    <image src='/images/notice.png'></image>
    <view class='xian'></view>
    <view class='notice container'>
          <view class='announcement-text' animation="{{animationData}}"> {{notice_content}}</view>
    </view>
</view>

css文件github

.contain{
  position: relative;
  width: 670rpx;
  height: 50rpx;
  line-height: 50rpx;
  background:rgba(253,253,253,1);
  margin: 20rpx auto 0;
   z-index: 10;
  font-size: 30rpx;
  overflow:auto;
  box-shadow:0px 0px 7rpx 0px rgba(83,152,95,0.18);
  border-radius:10rpx;
}
.contain image{
  display: inline-block;
  width: 30rpx;
  height: 30rpx;
  margin: 9rpx 25rpx;
}
.contain .xian{
  width: 2rpx;
  height: 36rpx;
  background: rgba(135,135,135,0.5);
  position: absolute;
  left: 80rpx;
  top:7rpx;
}
.contain .notice{
  position: absolute;
  z-index: 11;
  width: 538rpx;
  margin-left: 82rpx;
  padding: 0 25rpx;
  height: 36rpx;
  line-height: 36rpx;
  top: 7rpx;
  font-size: 26rpx;
  color: #888888;
  overflow: hidden;
}
.announcement-text {
  width: 538rpx;
  white-space: nowrap;
}

js文件小程序

const app = getApp()

Page({
  data: {
    // notice_content:'公告字幕滾動播放(文字跑馬燈效果),使用動畫和定時器完成,代碼片斷是一種迷你、可分享的小程序或小遊戲項目,可用於分享小程序和小遊戲的開發經驗',
    notice_content: '公告字幕滾動播放(文字跑馬燈效果),,,,,,,,使用動畫和定時器完成,代碼片斷是一種迷你、',
    animationData: {}, //公告動畫
  },
  onLoad: function () {
    let that = this;
    let reg = /[\u4e00-\u9fa5]/g;
    let text_con = that.data.notice_content;
    let textLen = text_con.length,
        textStrLen = text_con.match(reg).length;
        //計算有多少個,加一是爲了不內容沒有所有離開顯示框
    let hasStrLen = textStrLen + Math.ceil((textLen - textStrLen)/2)+1

    console.log(hasStrLen)
    let timeT = hasStrLen * 200
    console.log(timeT)
    //建立動畫實例
    var animation = wx.createAnimation({
      //此處以公告最長內容來設置動畫持續時間(duration:決定整個動畫播放的速度)
      duration: timeT,
      timingFunction: 'linear'
    });
    // //偏移距離爲公告內容的長度*字體大小(若字體大小使用rpx須要換算成px)
    animation.translate(-Number(hasStrLen * 13), 0).step();
    // animation.translate(-300, 0).step();
    that.setData({
      animationData: animation.export()
    });
    // 循環播放動畫關鍵步驟(使用兩個定時器)
    // 第一個定時器:將字幕恢復到字幕開始點(爲屏幕左邊),時間比初始值小,從新給animation賦值,刷新文字
    that.t1 = setInterval(function () {
      animation = wx.createAnimation({
        //此處以公告最長內容來設置動畫持續時間(duration:決定整個動畫播放的速度)
        duration: timeT,
        timingFunction: 'linear'
      });
      animation.translate(0, 0).step({ duration: 0 });
      that.setData({
        animationData: animation.export()
      });
    }.bind(that), timeT -1);
    // 第二個定時器:從新開始移動動畫,重置文本的位置
    that.t2 = setInterval(function () {
      animation.translate(-Number(hasStrLen * 13), 0).step();
      that.setData({
        animationData: animation.export()
      });
    }.bind(this), (timeT + 10) / 10);
  },
})
相關文章
相關標籤/搜索