截图展示:
进这个小程序就可以看到效果了
不啰嗦,直接上代码
WXML:
<veiw class="notice" bind:touchstart="noticetouchstart" bind:touchend="noticetouchend">
<view class="notice-content">
<view class="notice-content-text">{{noticeContent}}</view>
</view>
</veiw>
WXSS:
.notice{
padding: 45rpx 10rpx 10rpx 10rpx;
}
.notice-content-text{
transition: transform 0.8s;
font-size: 25rpx;
color: #000000;
white-space: nowrap;
text-align: center;
}
JS:
webview 模式下将JS代码里的内容,this.applyAnimatedStyle 这一个API去除。并将moveDistance 变量得到的值实时放入data里,再动态给notice-content元素的样式里
PS:最基本的小程序语法规则,还是要懂的。不懂的话。请先好好学习
data: {
noticeContent:''
},
methods: {
initNotice(){
//如果是在自定义组件或包含自定义组件的页面中,需要加上.in(this),不然会是null
var query=wx.createSelectorQuery().in(this);
//boundingClientRect 返回类名是notice的节点信息,从而得到容器宽度
query.select('.notice').boundingClientRect((res)=>{
this.noticeWidth=parseInt(res.width);
}).exec()
//原理同上,得到通知内容距离左边距的距离
query.select('.notice-content-text').boundingClientRect((res)=>{
const height = parseInt(res.height)
//根据元素高度,计算出单个字体大小
const fontSize = Math.round(height * 0.8);
//根据字体大小,计算出white-space: nowrap 通知内容的真实整体宽度
//因为white-space会让文本内容不换行,会有实际溢出宽度,需要计算它的溢出真实宽度
this.letterWidth=this.data.noticeContent.length*fontSize;
}).exec()
this.moveDistance = shared(0)
this.applyAnimatedStyle('.notice-content', () => {
'worklet'
return {
transform: `translateX(${this.moveDistance.value}px);`
}
})
clearInterval(this.noticeTimer)
this.moveContent();
},
moveContent(){
this.noticeTimer = setInterval(()=>{
if(this.letterWidth<=this.noticeWidth){
//通知文本内容宽度小于整个通知区域则不滚动
clearInterval(this.noticeTimer)
return
}
//向左滚动值大于通知内容的实际宽度(最左边),则继续向左滚动
if(this.moveDistance.value >= -this.letterWidth){
this.moveDistance.value = this.moveDistance.value-1
}else{
//不再小于通知内容的实际宽度时,从最右边滚出
this.moveDistance.value = this.noticeWidth
}
},35)
},
noticetouchstart(e){
clearInterval(this.noticeTimer)
},
noticetouchend(e){
this.moveContent();
}
}