noticeBar.js 2.94 KB
// components/marquee/marquee.js
let timer = null
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    data: {
      type: String,
      observer: function (n) {
        if (n) this.begin()
      }
    },
    delay: {
      type: Number,
      value: 1000
    },
    fontSize: {
      type: Number,
      value: 11
    },
    speed: {
      type: Number,
      value: 5000
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    flag: true,
    show: true
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取宽度
     */
    begin() {
      let boxWidth = 0
      let valueWidth = 0
      wx.p.wxApi.getViewInfo(
        '#marquee',
        res => {
          boxWidth = res.width
          this.setData({
            boxWidth
          })
          wx.p.wxApi.getViewInfo(
            '#content',
            contentInfo => {
              valueWidth = contentInfo.width
              if (boxWidth - 20 <= valueWidth) {
                this.setData({
                  valueWidth,
                  isRun: true
                })
                this.run()
              }
            },
            this
          )
        },
        this
      )
    },
    run() {
      clearTimeout(timer)
      let {
        speed,
        delay,
        valueWidth
      } = this.data
      let animation = wx
        .createAnimation({
          duration: speed,
          timingFunction: 'linear',
          delay
        })
        .left(`-${valueWidth}px`)
        .step()
      this.setData({
        animation: animation.export()
      })
      let time = Number(delay) + Number(speed) + 1000
      timer = setTimeout(() => {
        this.setData({
          flag: false
        })
        this.again()
      }, time)
    },
    again() {
      clearTimeout(timer)
      let {
        boxWidth
      } = this.data
      let animation = wx
        .createAnimation({
          duration: 1,
          timingFunction: 'linear'
        })
        .left(`${boxWidth}px`)
        .step()
      this.setData({
        animation: animation.export()
      })
      timer = setTimeout(() => {
        this.setData({
          flag: true
        })
        this.reset()
      }, 500)
    },
    reset() {
      clearTimeout(timer)
      let {
        valueWidth,
        boxWidth,
        speed
      } = this.data
      let animation = wx
        .createAnimation({
          duration: speed * (boxWidth / valueWidth).toFixed(2),
          timingFunction: 'linear'
        })
        .left('0%')
        .step()
      this.setData({
        animation: animation.export()
      })
      timer = setTimeout(() => {
        this.run()
      }, Number(speed) + 1000)
    },
  },
  pageLifetimes: {
    show: function () {
      this.setData({
        show: true
      })
      this.begin()
    },
    hide: function () {
      if (this.data.isRun) {
        this.reset()
        clearTimeout(timer)
        this.setData({
          show: false
        })
      }
    }
  }
})