美文网首页
实现文字超出横向滚动

实现文字超出横向滚动

作者: 源大侠 | 来源:发表于2022-11-22 16:35 被阅读0次

scrollText 组件

<template>
  <div class="marquee-wrap" ref="marquee-wrap">
    <div class="scroll" ref="scroll">
      <p class="marquee">{{text}}</p>
      <p class="copy" ref="copy"></p>
    </div>
    <p class="getWidth" ref="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
    }
    console.log(this.text)
    console.log(this.val)
  },
  methods: {
    move () {
    let maxWidth = this.$refs['marquee-wrap'].clientWidth
    let width = this.$refs['getWidth'].scrollWidth
      if (width <= maxWidth) return
    let scroll = this.$refs['scroll']
    let copy = this.$refs['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: 0.16rem;
  }
  p {
    word-break:keep-all;
    white-space: nowrap;
    font-size: 0.28rem;
  }
  .scroll {
    display: flex;
  }
  .getWidth {
    word-break:keep-all;
    white-space:nowrap;
    position: absolute;
    opacity: 0;
    top: 0;
  }
</style>

自定义头部信息中引用组件

<van-nav-bar
      right-text=""
      left-arrow
      fixed
      @click-left="onClickLeft"
    >
        <template #title>
          <scrollText :val="titleStr" v-if="!isLoading"></scrollText>
        </template>
    </van-nav-bar>

相关文章

网友评论

      本文标题:实现文字超出横向滚动

      本文链接:https://www.haomeiwen.com/subject/qolnxdtx.html