
vue开发tips:实现跑马灯【文字横向滚动】。
步骤:
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>大家放到开发软件里试试吧!





网友评论文明上网理性发言 已有0人参与
发表评论: