微信小程序文字循环滚动

在这里插入图片描述

<view class="marquee">
	<view class="main" style="transform: translateX({
       
       {
       
       move}}px);">
		种一颗树最好的时间是十年前,其次是现在
	</view>
</view>
.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;
}
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);
  },
})

猜你喜欢

转载自blog.csdn.net/AK852369/article/details/115356734
今日推荐