因为工作原因,需要用到自动滚动信息.所以在github上找了一款感觉还算不错的前端组件
这里是仓库地址https://github.com/satrong/vue-text-marquee
代码量很小。很容易扩展
因为业务原因,我对其做了点修改
TextMarquee.vue 组件
<template>
<!-- 这里, 我想添加个点击触发事件,这个事件默认是点击停止滚动,再点击则继续滚动,同样这个事件可以被覆盖,可以由外部传递的方法属性替换 -->
<div class="v-marquee" @click="onClickEvent()? animateSwitch = !animateSwitch : onClickEvent()">
<div :style="{'animation-duration':time,'animation-name':name}" :class="animateSwitch?'running':'pause'">
<!-- 这里是我添加的动效gif图,没有需求的可以不添加 -->
<img src="../../statics/remind-bell.gif" style="float: left; height: 28px; width: 28px; margin-right: 10px"/>
<slot>
<!-- 采用html显示 -->
<div style="float: left; line-height: 28px" v-html="content"></div>
</slot>
</div>
</div>
</template>
<script>
let count = 0;
export default {
name: 'VTextMarquee',
props: {
speed: { //速度
type: Number,
default: 50, //默认50
},
content: String, //内容
animate: { //开关
type: Boolean,
default: true, //默认开启
},
onClickEvent: { //点击消息体回调的方法, 默认返回true触发点击停止滚动,没有返回true则执行这个传递的方法
type: Function,
default: () => {
return true
}
},
},
data() {
count++;
return {
animateSwitch: this.animate,
time: 0,
name: 'marquee' + count,
styleEl: document.createElement('style'),
};
},
watch: {
animate(val){ //当外部开关发生变化,同步到内部开关
this.animateSwitch = val;
},
content() {
this.start();
},
speed() {
this.start();
},
},
methods: {
getTime() {
return Math.max(this.$el.firstChild.offsetWidth, this.$el.offsetWidth) / this.speed + 's';
},
prefix(key, value) {
return ['-webkit-', '-moz-', '-ms-', ''].map(el => `${el + key}:${value};`).join('');
},
keyframes() {
const from = this.prefix('transform', `translateX(${this.$el.offsetWidth}px)`);
const to = this.prefix('transform', `translateX(-${this.$el.firstChild.offsetWidth}px)`);
const v = `@keyframes ${this.name} {
from { ${from} }
to { ${to} }
}`;
this.styleEl.innerHTML = v;
document.head.appendChild(this.styleEl);
},
start() {
this.$nextTick(() => {
this.time = this.getTime();
this.keyframes();
});
},
},
mounted() {
this.start();
},
}
</script>
<style scoped>
.v-marquee {
white-space: nowrap;
overflow: hidden;
width: 100%;
}
.v-marquee > div {
display: inline-block;
animation: marquee linear infinite;
}
.v-marquee .pause {
animation-play-state: paused;
}
.v-marquee .running {
animation-play-state: running;
}
</style>
然后再需要调用到的页面导入即可。
components: {
VTextMarquee: () =>
import('./event/TextMarquee.vue') //横向滚动条,这里采用的是我们项目的导入方式。你们可以使用你们的导入方式
},
导入之后,再当前页面使用
<!-- onClickEvent 是替换的点击方法,不能返回结果。
animate 是初始化是否开始
speed 是滚动速度-->
<VTextMarquee style="margin-top: 10px" :onClickEvent="()=>{ $router.push({path:'/event-message',query:{eventId:data.id}})}"
:content="这里是滚动信息" :animate="true" :speed=50/>
这样就可以使用了