文字超出滚动效果封装为组件,,也页面多次使用封装

把封装组件的id换成ref就可以在同一个页面多次使用

组件在页面中使用

引用
import marquee from "@/components/marquee/index";
注册
  components:{
    marquee
  },
使用
<marquee :val="TI_info"></marquee>

组件代码

<template>
 <div ref="marqueeWrap" class="marquee-wrap">
     <!-- 文本超出滚动显示 -->
  <div ref="scroll" class="scroll">
   <p class="marquee">{{text}}</p>
   <p ref="copy" class="copy"></p>
  </div>
  <p ref="getWidth" 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 = this.$refs.marqueeWrap.clientWidth
   
   let width = this.$refs.getWidth.scrollWidth
   if (width <= maxWidth) return
   this.$refs.copy.innerText = this.text
   let distance = 0 
   this.timer = setInterval(() => {
    distance -= 1
    if (-distance >= width) {
     distance = 16
    }
    this.$refs.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;
 }
 .scroll {
  display: flex;
 }
 .getWidth {
  word-break:keep-all;
  white-space:nowrap;
  position: absolute;
  opacity: 0;
  top: 0;
 }
</style>
posted @ 2021-10-28 15:32  嗯哼Nymph  阅读(35)  评论(0编辑  收藏  举报