vue实现文字滚动效果

vue实现文字滚动效果

本文实例为大家分享了vue实现文字滚动效果的具体代码,供大家参考,具体内容如下

项目需求:系统公告,要从右忘左循环播放的牛皮广告效果。

实现:

方案一:使用定时器和CSS3的过渡属性来实现。

<template>   <div class="notice-card-wrapper">         <div id="message-wrap" ref="out" class="message">           <div id="con1" ref="con1" :class="{anim:animate==true}" style="margin-left: 2500px;">             <span v-html="notice"></span>           </div>         </div>   </div> </template>

关键标签ref='con1和内部的span,con1上面有一个anim样式,根据animate变量的变化来动态变化。
注意,我这里给了一个margin-left:2500px的初始位置

data() {     return {       animate: true,       notice: '',       intervalId: null // 定时器标识     }   },

定义需要的属性变量

mounted() {     this.scroll() // 动画先执行一次     this.intervalId = setInterval(this.scroll, 16000) // 间隔时间后重复执行   },   updated() {   },   destroyed() {     clearInterval(this.intervalId) // 清除定时器   },     methods: {     // 异步ajax获取公告内容,略过     handleFetchNotice() {       fetchNotice().then(res => {         this.notice = res.data.notice       }).catch(err => {         console.log(err)       })     },     // 定义动画     scroll() {       this.animate = true       const con1 = this.$refs.con1       setTimeout(() => {         con1.style.marginLeft = '-500PX'       }, 500)       setTimeout(() => {         con1.style.marginLeft = '2500px'         this.animate = false       }, 15000)     }   }

说明:执行动画函数,500ms后将refs.con1的margin-left值改为-500px,这个时候标签的过渡属性是ture,会动画显示这个变化过程。15000ms后,将margin-left值回到初始状态,过渡属性修改为false,动画切断。

最后一步,就算在css中定义过渡样式

<style lang="scss"> .anim{   transition: all 15s linear; } </style>

margin-left有2500px改为-500px的过程,过渡动画线性执行15s。

然后,定时器16000毫秒后,重复执行。

已修改为css3动画,简洁很多

<template>   <div class="notice-card-wrapper">     <div class="header">       <div class="title">         <!-- 系统公告 -->         <div class="message">           <div class="inner-container">             <span v-html="notice"></span>           </div>         </div>       </div>     </div>   </div> </template> <script> export default {   name: 'SystemNotice',   components: {   },   data() {     return {       notice: '我是广播文字内容,哈哈哈哈,你习惯不行啊,我页不知道啊啊啊啊啊'     }   },   computed: {   },   created() {   },   methods: {   } } </script> <style lang="scss" scoped> .notice-card-wrapper {   .inner-container {     margin-left: 100%; // 把文字弄出可见区域     width: 200%;     animation: myMove 30s linear infinite; // 重点,定义动画     animation-fill-mode: forwards;   }     /*文字无缝滚动*/   @keyframes myMove {     0% {       transform: translateX(0);     }     100% {       transform: translateX(-2500px);     }   }   } } </style>

推荐阅读