文字超出横向滚动组件
1.组件内容
<template>
<div class="marquee-wrap" ref="marquee-wrap">
<div class="scroll" ref="scroll">
<p class="marquee" ref="getWidth">{{text}}</p>
<p class="copy" ref="copy"></p>
</div>
</div>
</template>
<script>
export default {
name: 'marquee', // 文字超出横向滚动组件
props: ['val'],
data () {
return {
timer: null,
text: ''
}
},
created () {
let timer = setTimeout(() => {
this.move()
clearTimeout(timer)
}, 1000)
},
mounted () {
for (let item of this.val) {
this.text += item
}
},
methods: {
move () {
let maxWidth = this.$refs['marquee-wrap'].clientWidth
let width = this.$refs['getWidth'].clientWidth
if (width <= maxWidth) return
let scroll = this.$refs['scroll']
let copy = this.$refs['copy']
copy.innerText = this.text
let scrollWidth = width + copy.clientWidth // 需滚动距离
let distance = 0
this.timer = setInterval(() => {
distance -= 1
if (-distance >= scrollWidth) {
distance = 16
}
scroll.style.transform = 'translateX(' + distance + 'px)'
}, 20)
}
},
beforeDestroy () {
clearInterval(this.timer)
}
}
</script>
<style lang="scss" scoped>
.marquee-wrap {
width: 100%;
overflow: hidden;
position: relative;
top: -13px;
.scroll {
display: flex;
.copy{
margin-left: 20px;
}
}
p {
word-break: keep-all;
white-space: nowrap;
}
}
</style>
2.组件应用
<Marquee class="title" :val="card.title"></Marquee>

浙公网安备 33010602011771号