Vue开发组件之替代marquee标签,超出宽度文字横向滚动效果

2022-05-23 20:09:17 浏览数 (1)

一、npm 安装

如果你想安装插件(自己写的) 安装

install dependencies

npm i marquee-components

使用

在main.js引入

import marquee from ‘marquee-components’ Vue.use(marquee );

在页面使用

代码语言:javascript复制
<template>
  <div id="app">
       <marquee :val="msg"></marquee>
  </div>
</template>
<script>
export default {
  name: 'app',
  data () {
    return {
      msg: 'vuevuevuevuevuevuevuevuevuevuevuevuevuevuevuevuevue'
    }
  }
}
</script>
123456789101112131415

val后加文字即可,当超过文本容器长度时,触动横向滚动效果。 二、直接引入组件

代码语言:javascript复制
marquee组件

<template>
  <div class="marquee-wrap">
    <div class="scroll">
      <p class="marquee">{{text}}</p>
      <p class="copy"></p>
    </div>
    <p class="getWidth">{{text}}</p>
  </div>
</template>

<script>
export default {
  name: 'marquee',
  props: ['val'],
  data () {
    return {
      timer: null,
      text: ''
    }
  },
  created () {
    let timer = setTimeout(() => {
      this.move()
      clearTimeout(timer)
    }, 1000)
  },
  mounted () {
    for (let item of this.val) {
      this.text  = ' '   item
    }
  },
  methods: {
    move () {
      let maxWidth = document.querySelector('.marquee-wrap').clientWidth
      let width = document.querySelector('.getWidth').scrollWidth
      if (width <= maxWidth) return
      let scroll = document.querySelector('.scroll')
      let copy = document.querySelector('.copy')
      copy.innerText = this.text
      let distance = 0
      this.timer = setInterval(() => {
        distance -= 1
        if (-distance >= width) {
          distance = 16
        }
        scroll.style.transform = 'translateX('   distance   'px)'
      }, 20)
    }
  },
  beforeDestroy () {
    clearInterval(this.timer)
  }
}
</script>

<style scoped>
  .marquee-wrap {
    width: 100%;
    overflow: hidden;
    position: relative;
  }
  .marquee{
    margin-right: 16px;
  }
  p {
    word-break:keep-all;
    white-space: nowrap;
    font-size: 16px;
    font-family: "微软雅黑 Light";
  }
  .scroll {
    display: flex;
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119328082

0 人点赞