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