美文网首页
vue文字匀速走马灯显示

vue文字匀速走马灯显示

作者: 衬fzy | 来源:发表于2022-03-25 11:43 被阅读0次
image.png
<!-- 文字跑马灯 -->
<template>
  <div class="wrap">
    <div ref="box" class="box">
      {{ text }}
    </div>
  </div>
</template>
<script>
export default {
  props: {
    text: {
      type: [Array, Object],
      default: null
    }
  },
  data() {
    return {
      timer: null
    };
  },
  mounted() {
    this.startText();
  },
  destroyed() {
    this.stopText();
  },
  methods: {
    startText() {
      if (this.timer != null) return;
      let width = this.getLenPx(this.text, 13); // 第一个是文本,第二个参数是文本font-size值
      let distance = 100; // 从多少像素位置开始滚动
      this.timer = setInterval(() => {
        distance = distance - 1;
        // 如果位移超过文字宽度,则回到起点
        if (-distance >= width) {
          distance = 100; // 从多少像素位置开始滚动
        }
        this.$refs.box.style.transform = "translateX(" + distance + "px)";
      }, 20);
    },
    stopText() {
      // 清除定时器
      clearInterval(this.timer);
      // 清除定时器之后,需要重新将定时器置为null
      this.timer = null;
    },
    // 获取字符串占位px
    getLenPx(str, font_size) {
      var str_leng = str.replace(/[^\x00-\xff]/gi, "aa").length;
      return (str_leng * font_size) / 2;
    }
  }
};
</script>

<style lang="scss" scoped>
.wrap {
  width: 100%;
  overflow: hidden;
}

.box {
  width: 600%;
  overflow: hidden;
}
</style>

使用方式:

<div><Txt :text="item.name"></Txt></div>
import Txt from "./txt";
components: { Txt },

感谢大家点赞!

相关文章

网友评论

      本文标题:vue文字匀速走马灯显示

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