vue__文字超出长度之后跑马灯

1、新建一个名为marquee.vue的文件,代码如下

复制代码
<template>
    <div class="scrollText" ref="outer">
        <div class="st-inner" :class="{'st-scrolling': needToScroll}">
            <span class="st-section" ref="inner">{{text}}</span>
            <span class="st-section" v-if="needToScroll">{{text}}</span>
            <!-- 加两条是为了滚动的时候实现无缝衔接 -->
        </div>
    </div>
</template>
<script>
export default {
  data () {
    return {
      needToScroll: false,
      text: ''
    }
  },
  mounted () {
    this.startCheck()
  },
  beforeDestroy () {
    this.stopCheck()
  },
  methods: {
    // 检查当前元素是否需要滚动
    check () {
      this.setText()
      this.$nextTick(() => {
        let flag = this.isOverflow()
        this.needToScroll = flag
      })
    },
 
    // 判断子元素宽度是否大于父元素宽度,超出则需要滚动,否则不滚动
    isOverflow () {
      let outer = this.$refs.outer
      let inner = this.$refs.inner
      let outerWidth = this.getWidth(outer)
      let innerWidth = this.getWidth(inner)
      return innerWidth > outerWidth
    },
 
    // 获取元素宽度
    getWidth (el) {
      let { width } = el.getBoundingClientRect()
      return width
    },
 
    // 获取到父组件传过来的内容复传给this.text
    setText () {
      this.text =
        (this.$slots.default &&
          this.$slots.default.reduce((res, it) => res + it.text, '')) ||
        ''
    },
 
    // 增加定时器,隔一秒check一次
    startCheck () {
      this._checkTimer = setInterval(this.check, 1000)
      this.check()
    },
 
    // 关闭定时器
    stopCheck () {
      clearInterval(this._checkTimer)
    }
  }
}
</script>
<style scoped>
.scrollText {
  overflow: hidden;
  white-space: nowrap;
}
.st-inner {
  display: inline-block;
}
.st-scrolling .st-section {
  padding: 0 30px;
}
 
 /* 向左匀速滚动动画 */
.st-scrolling {
  animation: scroll 10s linear infinite;
}
 
@keyframes scroll {
  0% {
    transform: translate3d(0%, 0, 0);
  }
  100% {
    transform: translate3d(-50%, 0, 0);
  }
}
</style>
复制代码

2、在你需要用到它的地方引入:

复制代码
<div class="scroll_box"><marquee> 我是一个跑马灯跑马灯跑马灯跑马灯跑马灯....... </marquee></div>
<script>
   import marquee from './marquee.vue'
   export default { 
     components: {
       marquee
     },
   }

</script>
复制代码
//这里设置的宽度就是文字长度超过30px后就自动滚动
<style scoped> .scroll_box { width: 30px; } </style>

 

posted @   会转圈圈的哆瑞米  阅读(786)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示