您的位置:首页 > Web前端 > Vue.js

Vue实现跑马灯样式文字横向滚动

2021-11-28 04:06 661 查看

本文实例为大家分享了Vue实现跑马灯样式文字横向滚动的具体代码,供大家参考,具体内容如下

需求:

在Vue项目的顶部,来实现文字左右滚动

步骤:

1、可以自己封装一个组件,也可以自己写,也可以复制以下代码
2、封装完成以后要在所需的组件中引入,注册,并使用

代码:

封装一个专门用来实现跑马灯效果的组件marquee组件

<template>
<!-- 跑马灯组件 -->
<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>
</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)
}
}
</script>

<style scoped>
.marquee-wrap {
width: 100%;
overflow: hidden;
position: relative;
}
.marquee{
margin-right: 0.16rem;
}
p {
word-break:keep-all;
white-space: nowrap;
font-size: 0.28rem;
}
.scroll {
display: flex;
}
.getWidth {
word-break:keep-all;
white-space:nowrap;
position: absolute;
opacity: 0;
top: 0;
}
</style>

在哪个组件中使用,就引入

// 引入跑马灯组件
import  marquee  from "@/components/marquee/marquee.vue";

引用并注册

export default {
components: {
// 注册跑马灯组件
marquee,
},
}

注册完成以后接下来就是Html样式了,在template模板中使用这个组件

<Marquee class="realData">
<ul class="fa-scroll-cont">
<li v-for="item in realData" :key="item.name">
<span class="roll-text">{{ item.city }}</span>
</li>
</ul>
</Marquee>

接下来就是效果图:

为了效果看的更明显多截了几张

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue 跑马灯 滚动