微信小程序文字跑马灯组件

wxml
<scroll-view class="marquee-container">
  <view class="scroll-txt">
    <view class="marquee-box">
      <view class="marquee-text" style="transform: translateX(-{{ marqueeDistance }}px)">
        <text>{{ marqueeText }}</text>
        <text style="margin-right:{{ marqueeMargin }}px;"></text>
        <text style="margin-right:{{ marqueeMargin }}px;">{{ marqueeText }}</text>
      </view>
    </view>
  </view>
</scroll-view>
js
Component({
  properties: {
    marqueeText: {
      type: String,
      value: ''
    },
    textSize: {
      type: Number,
      value: 12 // 单位 rpx
    },
    marqueePace: { // 滚动速度
      type: Number,
      value: 1,
    },
    marqueeMargin: { //滚动条每次出现时距离左边位置,默认屏幕宽度
      type: Number,
      value: 30
    },
  },
  data: {
    marqueeDistance: 10, //初始滚动距离
    timer: '',// 定时器
  },
  attached() {
    this.init();
  },
  methods: {
    init() {
      const { marqueeText, textSize } = this.data;
      const textLength = marqueeText.length * textSize;
      const { windowWidth }  = wx.getSystemInfoSync()
      this.setData({ textLength, windowWidth });
      this.scrollTxt();
    },
    scrollTxt() {
      let { textLength, windowWidth, timer, marqueeMargin, marqueePace } = this.data;
      if (textLength > windowWidth) {
        timer = setInterval(() => {
          const maxScrollWidth = textLength + marqueeMargin;
          const left = this.data.marqueeDistance;
          if (left < maxScrollWidth) {
            this.setData({ marqueeDistance: left + marqueePace });
          } else {
            this.setData({ marqueeDistance: 0 });
            clearInterval(timer);
            this.scrollTxt();
          }
        }, 20);
      } else {
        this.setData({ marqueeMargin: '1000' });
      }
      this.setData({ timer });
    }
  },
  pageLifetimes: {
    show() {
      this.init();
    },
    hide() {
      clearInterval(this.data.timer);
    },
  }
});
wxss
.marquee-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-sizing: border-box;
  height: 100%;

  .scroll-txt {
    padding: 0 20rpx;

    .marquee-box {
      position: relative;
      display: block;

      .marquee-text {
        position: absolute;
        top: 0;
        white-space: nowrap;
      }
    }
  }
}
json
{
  "component": true
}
使用
wxml:
<marquee-text class="notice-text" marqueeText="{{ '测试跑马灯内容很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长很长' }}" textSize="{{ 28 }}"></marquee-text>
wxss:
.notice-text {
 width: 100%;
 font-size: 28rpx;
}
json:
{
  "usingComponents": {
    "marquee-text": "/components/marquee-text/index"
  }
}

参考链接: https://blog.csdn.net/crabfrog/article/details/82768097

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值