效果图
<template>
<div class="maq-div">
<img class="icon-alarm" src="../assets/image/horn.png" />
<div class="marquee-wrap" ref="marquee-wrap">
<div class="scroll" ref="scroll">
<p class="marquee">{{ text }}</p>
<p class="copy" ref="copy"></p>
</div>
<p class="getWidth" ref="getWidth">{{ text }}</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'].scrollWidth
if (width <= maxWidth) return
let scroll = this.$refs['scroll']
let copy = this.$refs['copy']
copy.innerText = this.text
let distance = 0
this.timer = setInterval(() => {
distance -= 1
if (-distance >= width) {
distance = 16
}
scroll.style.transform = 'translateX(' + distance + 'px)'
}, 20)
},
},
beforeDestroy() {
clearInterval(this.timer)
this.timer = null
},
}
</script>
<style scoped>
.maq-div{
width: 100%;
height: 74px;
line-height: 74px;
background: #171717;
border-radius: 13px;
padding-left: 10px;
}
.icon-alarm {
margin: 17px 20px 0 10px;
width: 40px;
height: 40px;
float: left;
}
.marquee-wrap {
float: left;
width: calc(100% - 80px);
height: 74px;
line-height: 74px;
overflow: hidden;
position: relative;
}
.marquee {
margin-right: 0.16rem;
}
p {
word-break: keep-all;
white-space: nowrap;
font-size: 0.28rem;
color: #fff;
}
.scroll {
display: flex;
}
.getWidth {
word-break: keep-all;
white-space: nowrap;
position: absolute;
opacity: 0;
top: 0;
}
</style>
调用
<marquee :val="list" />
list: ["欢迎大家来一起学习","在一起学习","一起学习","学无止境"],