最近在uniapp项目中有遇到一个需要在底部的文字单行显示并在文字超出屏幕后自动滚动。 这里记录一下相关实现流程
直接上干货
index.vue 页面
<template>
<view class="base">
<view id="bottom-content" class="bottom-content">
<text id="bottom-text" :style="{ animation: `wordsLoop ${scrollTime}s linear infinite normal` }">{{ content }}</text>
</view>
</view>
</template>
<script>
export default {
data() {
return {
scrollTime: 0,
pWidth: 0,
cWidth: 0,
content: ''
};
},
mounted() {
//计算滚动文字的父控件的宽度,这个宽度在页面渲染完成后就有了
const query = uni.createSelectorQuery().in(this);
query
.select('#bottom-content')
.boundingClientRect(data => {
this.pWidth = data.width;
})
.exec();
//模拟网络请求后获得滚动文字内容
setTimeout(() => {
this.content =
'纤云弄巧,飞星传恨,银汉迢迢暗度。金风玉露一相逢,便胜却、人间无数。柔情似水,佳期如梦,忍顾鹊桥归路!两情若是久长时,又岂在、朝朝暮暮。—出自宋代秦观《鹊桥仙·纤云弄巧》';
//这一句很重要,不然滚动不生效
this.$nextTick(() => {
this.initScrollTime();
});
}, 1500);
},
methods: {
initScrollTime() {
const query = uni.createSelectorQuery().in(this);
query
.select('#bottom-text')
.boundingClientRect(data => {
this.cWidth = data.width;
if (this.cWidth > 0 && this.pWidth < this.cWidth) {
this.scrollTime = (this.cWidth / 260).toFixed(2); //动画过渡时间
console.log('this.scrollTime', this.scrollTime);
}
})
.exec();
}
}
};
</script>
<style scoped lang="scss">
.base {
width: 100vw;
height: 100vh;
background-color: #007aff;
.bottom-content {
color: #ffffff;
font-weight: bold;
font-size: 4vw;
overflow-x: hidden; //这一句很重要
text {
// /* 文本现在单行 */
white-space: nowrap;
/* 滚动 */
display: inline-block;
}
}
}
</style>
App.vue 页面中的style中添加动画
<script>
export default {
onLaunch: function() {
console.log('App Launch');
},
onShow: function() {
console.log('App Show');
},
onHide: function() {
console.log('App Hide');
}
};
</script>
<style>
/*每个页面公共css */
//如果想要在vue页面动态绑定style中使用动画,这个动画必须写在这里,这是教训,切记!!!
@keyframes wordsLoop {
0% {
transform: translateX(0px);
-webkit-transform: translateX(0px);
}
100% {
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
}
@-webkit-keyframes wordsLoop {
0% {
transform: translateX(0px);
-webkit-transform: translateX(0px);
}
100% {
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
}
</style>
注意:如果想要在vue页面动态绑定style中使用动画,这个动画必须写在App.vue页面,切记!!! 就这两个类 copy出来直接运行,看看逻辑,然后举一反三的实现其他方向的滚动。