一、前言
如上图所示,左边固定两个图标,右边固定一个图标,中间内容滚动,但是注意,一般的UI框架是提供滚动组件的,但是为什么要自己实现,主要是因为一般的UI组件不提供文字无缝连接,什么意思,假设滚动文字为:别人都知道我是一个超级无敌帅哥。一般的UI组件:等到无敌帅哥滚动玩,别人才会出现,所以就出现了一段空白,而我们的需求是,滚动到无敌帅哥之后,后面接上了别人都知道,无缝连接继续滚动,因为CSDN上传视频上传不了,就离谱,就简单描述了一下。
二、实现
notice.vue(滚动组件)
<template>
<div class="notice">
<div class="notice-img">
<img class="notice-img1" src="@/assets/image/notice1.png" />
<img class="notice-img2" src="@/assets/image/notice2.png" />
</div>
<div class="notice-wrap">
<p>{
{
notify }}</p>
<p class="notice-copy"></p>
</div>
<p class="notice-getWidth">{
{
notify }}</p>
<div class="notice-img notice-image">
<img class="notice-img3" src="@/assets/image/rightarrow_more.png" />
</div>
</div>
</template>
<script>
export default {
name: "Notice",
props: ["notify"],
data() {
return{
timer: null
}
},
methods: {
move() {
let maxWidth = document.querySelector(".notice").clientWidth;
let width = document.querySelector(".notice-getWidth").scrollWidth;
if(width<maxWidth) return
let scroll = document.querySelector(".notice-wrap");
let copy = document.querySelector('.notice-copy');
copy.innerText = this.notify
let distance = 0; // 位移距离
this.timer = setInterval(() => {
distance -= 1;
if(-distance >= width) {
// 如果位移超过文字宽度,则回到起点
distance = 14; // 与滚动字体保持一直就行
}
scroll.style.transform = `translateX(${
distance}px)`
},20)
},
},
beforeDestroy() {
debugger
if(this.timer) {
clearInterval(this.timer)
}
},
watch: {
notify(newVal) {
if (newVal) {
const _this = this
let timer = setTimeout(() => {
_this.move();
clearTimeout(timer);
}, 1000);
}
},
},
};
</script>
<style lang="scss" scoped>
.notice {
display: flex;
overflow: hidden;
position: relative;
height: 108px;
border-top: 14px solid #f0f0f0;
border-bottom: 14px solid #f0f0f0;
font-size: 14PX;
.notice-img {
display: flex;
align-items: center;
position: relative;
z-index: 2;
background: #fff;
.notice-img1 {
width: 30px;
height: 32px;
margin-left: 24px;
margin-right: 16px;
}
.notice-img2 {
width: 100px;
height: 40px;
margin-right: 12px;
}
.notice-img3 {
width: 17px;
height: 34px;
}
}
.notice-image{
width: 100px;
justify-content: center;
}
.notice-wrap {
display: flex;
align-items: center;
white-space: nowrap;
word-break: keep-all;
width: calc(100% - 241px);
.notice-copy{
margin-left: 32px;
}
}
.notice-getWidth{
word-break: break-all;
white-space: nowrap;
position: absolute;
opacity: 0;
top: 0;
}
}
</style>