效果图
VUE组件封装
<template>
<div class="marquee" :style="{ backgroundColor: bgColor, height: height + 'px' }">
<span class="marquee__title" ref="marqueeTitle" :style="{ color, fontSize: fontSize + 'px', animationDuration: speed + 's', '--speed': speed }" v-html="title"></span>
</div>
</template>
<script>
export default {
name: 'NoticeBar',
props: {
content: {
type: String,
default: ''
},
color: {
type: String,
default: '#EFF0DB'
},
fontSize: {
type: Number,
default: 40
},
speed: {
type: Number,
default: 0
},
bgColor: {
type: String,
default: '#CC2529'
},
height: {
type: Number,
default: 78
}
},
data() {
return {
DEFAULT_SPEED: 143,
title: ''
};
},
watch: {
content(value) {
this.title = value;
this.calcSpeed();
}
},
created() {
if (this.content) {
this.title = this.content;
this.calcSpeed();
}
},
methods: {
calcSpeed() {
if (this.title !== '' && this.speed === 0) {
this.$nextTick(() => {
let width = this.$refs.marqueeTitle.clientWidth;
this.speed = Number(width / this.DEFAULT_SPEED).toFixed(2);
});
}
}
}
};
</script>
<style scoped="scoped">
.marquee {
display: flex;
align-items: center;
box-sizing: border-box;
word-break: break-all;
white-space: nowrap;
overflow: hidden;
}
.marquee__title {
letter-spacing: 3px;
cursor: default;
display: inline-block;
padding-left: 100%;
animation: marqueeMove calc(var(--speed) * 1s) linear infinite;
}
.marquee:hover .marquee__title {
animation-play-state: paused;
}
@keyframes marqueeMove {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
</style>
使用方式
<template>
<div id="app">
<NoticeBar v-if="marquee.cont" :content="marquee.cont"></NoticeBar>
</div>
</template>
<script>
import NoticeBar from './components/NoticeBar.vue';
export default {
name: 'app',
components: {
NoticeBar
},
data() {
return {
marquee: {
cont: '祝大家兔年快乐,身体健康!'
}
};
}
};
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>