title: 实现一个从左到右的通知滚动组件
date: 2023-01-31 11:19:52.353
updated: 2023-01-31 11:22:39.786
url: https://hexo.start237.top/archives/实现一个从左到右的通知滚动组件
categories:
- IT技术
tags: - vue
技术栈使用
vue2
开发思路
- 创建一个div具有固定的宽度,宽度样式为100%
- 包裹一个div,长度是通知内容的长度。样式设置为 inline-block,行内块元素,并且不允许换行。
- 用CSS创建一个从左到右的动画。
- 通知内容的div调用CSS动画。
需要调整注意的细节
- 通知从左到右滚动速度的问题。因为内容宽度是不固定的,通过内容的宽度求出需要滚动的速度,计算出动画的时长。避免把动画时长写死,导致字数多了,视觉上速度变快的问题。
- 通知初始位置的问题。一般通知内容需要从左到右划出,所以,初始位置不能够在一开始就固定显示在屏幕上,而是从父元素的最右边出来。把以需要通知 ref 属性获取到内容父元素的宽度。来设置内容元素的左边距,并且,动画结束的位置需要用 100% - 左边距的距离。
#技术点知识
this.$refs
css变量
js设置css变量方法 el.style.setProperty
代码实现
<style scoped lang="less">
@import "../styles/color";
@keyframes tranX {
from {
transform: translateX(0%);
}
to {
transform: translateX(calc(-100% - var(--notice-offset)));
}
}
.notice {
width: 100%;
--notice-offset: 490px;
--second: 10s;
flex: 1;
box-sizing: border-box;
padding: 0 10px;
line-height: 30px;
overflow: hidden;
display: flex;
align-items: center;
.context {
font-size: 18px;
box-sizing: border-box;
color: red;
white-space: nowrap;
margin-left: var(--notice-offset);
animation: tranX var(--second) linear infinite;
display: inline-block;
}
}
</style>
<template>
<div ref="notice" class="notice">
<div class="context">
{{ text }}
</div>
</div>
</template>
<script>
import noticePng from '../assets/images/tabbar/notice.png'
export default {
name: 'notice',
props: {
text: {
type: String,
required: true,
}
},
data () {
return {
noticePng,
}
},
mounted () {
this.init()
},
methods: {
async init () {
},
initAnimated () {
const el = this.$refs.notice
el.style.setProperty('--notice-offset', el.clientWidth + 'px')
const contextWidth = el.querySelector('.context').clientWidth
console.log(el.querySelector('.context').clientWidth)
//调整系数宽度越大,速度越慢
const coefficient = Math.floor(contextWidth / 17.1) + 's'
el.style.setProperty('--second', coefficient)
}
},
watch: {
text: function () {
this.$nextTick(() => {
this.initAnimated()
})
}
}
}
</script>