微信小程序文字循环滚动

2021-04-02 09:53:29 浏览数 (1)

代码语言:javascript复制
<view class="marquee">
	<view class="main" style="transform: translateX({{move}}px);">
		种一颗树最好的时间是十年前,其次是现在
	</view>
</view>
代码语言:javascript复制
.marquee {
  position: relative;
  width: 100%;
  height: 50rpx;
  line-height: 50rpx;
  white-space: nowrap;
  overflow: hidden;
  font-size: 24rpx;
  color: #fff;
  background: lightcoral;
}

.main {
  position: absolute;
}
代码语言:javascript复制
Page({
  data: {
    marWidth: 0,
    mainWidth: 0,
    move: 0,
    timer: "",
  },

  onLoad: function () {
    this.initMarquee()
  },

  initMarquee() {
    let query = wx.createSelectorQuery();
    // 获取装载体、文字的宽度
    query.select('.marquee').boundingClientRect((res) => {
      this.data.marWidth = parseInt(res.width)
    }).exec()
    query.select('.main').boundingClientRect((res) => {
      this.data.mainWidth = parseInt(res.width)
      this.moveText()
    }).exec()
  },

  moveText() {
    this.data.timer = setInterval(() => {
      // 每50毫秒移动0.5px
      this.setData({
        move: this.data.move - 0.5
      })
      // 如果完全移动,重新到后移
      if (parseInt(this.data.move) == -this.data.mainWidth) {
        this.setData({
          move: this.data.marWidth
        })
        clearInterval(this.data.timer)
        this.moveText()
      }
    }, 50);
  },
})

0 人点赞