marquee.js 2.7 KB
// components/marquee/marquee.js
let timer = null
import util from '../../utils/util.js'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    data: {
      type: String,
      value: '测试公告'
    },
    delay: {
      type: Number,
      value: 1000
    },
    fontSize: {
      type: Number,
      value: 12
    },
    speed: {
      type: Number,
      value: 5000
    }
  },

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

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取宽度
     */
    getWidth() {
      let boxWidth = 0
      let valueWidth = 0
      util.getViewInfo('#marquee', res => {
        boxWidth = res.width
        this.setData({
          boxWidth
        })
        util.getViewInfo('#content', contentInfo => {
          valueWidth = contentInfo.width
          if (boxWidth - 20 <= valueWidth) {
            this.setData({
              valueWidth
            })
            this.run()
          }
        }, this)
      }, this)
    },
    run() {
      clearTimeout(timer)
      util.promise(resolve => {
        let {
          speed,
          delay,
          valueWidth
        } = this.data
        let animation = wx.createAnimation({
          duration: speed,
          timingFunction: 'linear',
          delay
        })
        animation.left(`-${valueWidth}px`).step()
        this.setData({
          animation: animation.export()
        })
        let time = Number(delay) + Number(speed) + 1000
        timer = setTimeout(() => {
          resolve()
        }, time)
      }).then(() => {
        this.setData({
          flag: false
        })
        this.again()
      })

    },
    again() {
      clearTimeout(timer)
      util.promise(resolve => {
        let {
          boxWidth
        } = this.data
        let animation = wx.createAnimation({
          duration: 1,
          timingFunction: 'linear'
        })
        animation.left(`${boxWidth}px`).step()
        this.setData({
          animation: animation.export()
        })
        timer = setTimeout(() => {
          resolve()
        }, 500)
      }).then(() => {
        this.setData({
          flag: true
        })
        this.goZero()
      })

    },
    goZero() {
      clearTimeout(timer)
      util.promise(resolve => {
        let {speed} = this.data
        let animation = wx.createAnimation({
          duration: speed,
          timingFunction: 'linear',
        })
        animation.left('0%').step()
        this.setData({
          animation: animation.export()
        })
        timer = setTimeout(() => {
          resolve()
        }, Number(speed) + 5000)
      }).then(() => {
        this.run()
      })
    }
  },
  ready(){
    this.getWidth()
  }
})