微信小程序从右向左无限滚动组件封装(类似公告)

发布于:2025-03-14 ⋅ 阅读:(16) ⋅ 点赞:(0)

组件代码

wxml代码

<view class="container">
    <view class="text-wrapper">
        <!-- 这两个都不能删除,用来放无限滚动的,第一个滚完第二个接上,第二个滚完第一个又接上了 -->
        <text class="scroll-text text1" style="left: {{-moveleft}}px;">{{ scrollText }}</text>
        <text class="scroll-text text2" style="left: {{ moveleft2}}px;">{{ scrollText }}</text>
    </view>
</view>

wxss代码

.container {
    display: flex;
    width: 100vw;
}

.text-wrapper {
    display: flex;
    width: 100vw;
    height: 50rpx;
    overflow: hidden;
    position: relative;
    margin-right: 20rpx;
    margin-left: 20rpx;
}

.scroll-text {
    white-space: nowrap;
}

.text1 {
    position: absolute;
    white-space: pre;
    font-size: 26.37rpx;
    line-height: 28rpx;
    color: #FAEECC;
}

.text2 {
    position: absolute;
    white-space: pre;
    font-size: 26.37rpx;
    line-height: 28rpx;
    color: #FAEECC;
}

js代码

Component({
    /**
     * 组件的属性列表
     */
    properties: {
      // 两文本的内容间隔
      interval_widgth: {
        type: Number,
        value: 10
      },
      scrollText:{
        type:String,
        value:'这里是需要无缝滚动的文本,用于检测滚动效果是否正常!'
      }
    },
   
    /**
     * 组件的初始数据
     */
    data: {
   
      moveleft:0,
      moveleft2:0,
      text_width:0,
      timer:null
    },
   
    /**
     * 组件的方法列表
     */
    methods: {
   
    },
    lifetimes: {
      attached() {
      },
      ready() {
        // 获取内容的宽度
        const query = wx.createSelectorQuery().in(this);
        query.select('.scroll-text').boundingClientRect().exec((res) => {
          this.setData({
            'text_width':res[0].width,
            moveleft2: res[0].width+this.data['interval_widgth']
          })
        });
      },
      detached(){
        clearInterval(this.data.timer);
      }
    },
    pageLifetimes: {
      show() {
        this.data.timer=setInterval(()=>{
          if(this.data.moveleft>=this.data.text_width+this.data.interval_widgth){
            this.setData({
              moveleft:-(this.data.interval_widgth+this.data.text_width)
            })
          };
          if(-(this.data.moveleft2)>=this.data.text_width+this.data.interval_widgth){
            this.setData({
              moveleft2:(this.data.interval_widgth+this.data.text_width)
            })
          };
          this.setData({
            moveleft:this.data.moveleft+2,
            moveleft2:this.data.moveleft2-2
          })
        },20)
       
      },
      hide(){
        clearInterval(this.data.timer);
      }
    }
  })

页面使用

在页面的json文件引入组件

{
    "usingComponents": {
        "gundong": "../../components/gundong/gundong"
    }
}

使用

<gundong></gundong>

这里也支持传值,如果封装的值或者样式不满足需求可以修改组件传入更多数据,不影响滚动功能即可