实现一个从左到右的通知滚动组件

该文章介绍了如何使用Vue2开发一个从左到右滑动的通知组件。通过创建包含内容的div并利用CSS动画实现滚动效果,动态计算滚动速度以适应不同长度的内容,确保通知始终从屏幕右侧出现。同时,文章提到了使用`this.$refs`和CSS变量来设置和调整动画参数。
摘要由CSDN通过智能技术生成

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

开发思路

  1. 创建一个div具有固定的宽度,宽度样式为100%
  2. 包裹一个div,长度是通知内容的长度。样式设置为 inline-block,行内块元素,并且不允许换行。
  3. 用CSS创建一个从左到右的动画。
  4. 通知内容的div调用CSS动画。

需要调整注意的细节

  1. 通知从左到右滚动速度的问题。因为内容宽度是不固定的,通过内容的宽度求出需要滚动的速度,计算出动画的时长。避免把动画时长写死,导致字数多了,视觉上速度变快的问题。
  2. 通知初始位置的问题。一般通知内容需要从左到右划出,所以,初始位置不能够在一开始就固定显示在屏幕上,而是从父元素的最右边出来。把以需要通知 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>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值