用vue实现文字滚动
可以使用vue的transition组件和CSS的animation来实现文字滚动效果。
- 创建一个组件,命名为TextScroll.vue:
<template>
<div class="text-scroll">
<transition name="scroll">
<span :style="scrollStyle">{{ text }}</span>
</transition>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true
},
duration: {
type: Number,
default: 5000
}
},
data() {
return {
scrollStyle: {
animationDuration: `${this.duration}ms`,
animationTimingFunction: 'linear',
animationIterationCount: 'infinite',
animationName: 'scroll-text'
}
}
}
}
</script>
<style>
.text-scroll {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
@keyframes scroll-text {
from { transform: translateX(0); }
to { transform: translateX(-100%); }
}
.scroll-enter-active,
.scroll-leave-active {
animation-duration: 0.5s;
animation-timing-function: ease;
animation-fill-mode: forwards;
}
.scroll-enter,
.scroll-leave-to {
opacity: 0;
}
</style>
- 在父组件中使用TextScroll组件:
<template>
<div class="container">
<text-scroll text="这是一段需要滚动的文字" />
</div>
</template>
<script>
import TextScroll from './TextScroll.vue'
export default {
components: {
TextScroll
}
}
</script>
<style>
.container {
width: 200px;
height: 50px;
}
</style>
在这个例子中,TextScroll组件接收两个props:text表示需要滚动的文本,duration表示滚动的时长,默认为5000毫秒。组件内部使用了CSS的animation来实现文本滚动效果,同时使用了vue的transition组件来实现动画过渡效果。在父组件中引入TextScroll组件,传入需要滚动的文本即可。
原文地址: http://www.cveoy.top/t/topic/beKO 著作权归作者所有。请勿转载和采集!