最近项目上有一个文字跑马灯的需求,在平台上看了很多类似的,大多数不满足需求,于是博众家所长,利用 Js + Css 动画来解决此问题,实现了文字跑马灯无缝滚动
组件源码
<template>
<div class="outBox" ref="outBox">
<div ref="box" :class="textOverflow && 'outBox_warp'">
<p>{{ textWard }}</p>
<p v-show="textOverflow">{{ textWard }}</p>
</div>
</div>
</template>
<script>
export default {
props: {
// 传递过来的字符串
textWard: {
type: String,
default: ""
},
},
data () {
return {
textOverflow: false
}
},
watch: {
textWard () {
this.$nextTick(() => {
this.renderDom()
})
}
},
mounted () {
this.$nextTick(() => {
this.renderDom()
})
},
methods: {
renderDom () {
// 获取外面盒子的Dom元素
const outBox = this.$refs.outBox
const outWidth = outBox.offsetWidth
// 获取里面面盒子的Dom元素
const box = this.$refs.box
// 获取第一个子元素的宽度
const childWidth = [...box.childNodes][0].offsetWidth
// 对比子元素宽度和外部盒子宽度,设置是否滚动
if (childWidth > outWidth) {
this.textOverflow = true
} else {
this.textOverflow = false
}
},
// 完善功能
}
}
</script>
<style lang="less" scoped>
.outBox {
width: 100%;
display: -ms-flexbox;
display: flex;
-ms-flex-positive: 1;
flex-grow: 1;
overflow: hidden;
&_warp {
-ms-flex: none;
flex: none;
display: -ms-flexbox;
display: flex;
-ms-flex-align: center;
align-items: center;
animation: move-data 12s 0.5s linear infinite;
p {
padding-right: 40px;
}
}
@keyframes move-data {
0% {
transform: translateX(0);
}
to {
transform: translateX(-50%);
}
}
}
</style>
demo测试(外层容器需要设置宽度)
<span :style=" width: 100px">
<TextScroll :textWard="测试文字测试文字测试文字测试文字测试文字测试文字" />
</span>