这篇文章主要介绍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如何实现跑马灯样式文字横向滚动”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。