VciTextRoll.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <template>
  2. <div
  3. class="VciTextRoll"
  4. @mouseenter="stop"
  5. @mouseleave="roll"
  6. >
  7. <div
  8. :class="{'vci-transition' : !enableRoll}"
  9. :style="{ transform: `translateX(${offset}px)` }"
  10. class="tr-view vci-flex-rml"
  11. >
  12. <span
  13. ref="text"
  14. :title="text"
  15. class="tr-text"
  16. >
  17. {{ text }}
  18. </span>
  19. <span
  20. v-if="enableRoll"
  21. :title="text"
  22. class="tr-text-fill"
  23. >
  24. {{ text }}
  25. </span>
  26. </div>
  27. </div>
  28. </template>
  29. <script>
  30. import MixinClearScheduleTasks from "../../mixins/MixinClearScheduledTasks";
  31. import { addCss, getElementPropertyOfNumber } from "@vci/helper/src/element";
  32. export default {
  33. name: "VciTextRoll",
  34. mixins: [MixinClearScheduleTasks],
  35. props: {
  36. text: {
  37. default: "文字滚动",
  38. type: [String, Number, Boolean]
  39. },
  40. speed: {
  41. type: Number,
  42. default: 0.6
  43. },
  44. forceRoll: {
  45. type: Boolean,
  46. default: false
  47. },
  48. debug: {
  49. type: Boolean,
  50. default: false
  51. }
  52. },
  53. data() {
  54. return {
  55. offset: 0,
  56. enableRoll: false,
  57. inter: {
  58. resize: -1,
  59. roll: -1
  60. }
  61. };
  62. },
  63. watch: {
  64. text: {
  65. handler: "roll",
  66. immediate: true
  67. }
  68. },
  69. mounted() {
  70. window.addEventListener("resize", this.roll);
  71. this.$once("hook:beforeDestroy", () => window.removeEventListener("resize", this.roll));
  72. },
  73. methods: {
  74. roll() {
  75. this.stop();
  76. this.$nextTick(() => {
  77. const el = this.$el;
  78. const elText = this.$refs.text;
  79. if(this.forceRoll) {
  80. const widthMax = getElementPropertyOfNumber(el, "maxWidth");
  81. (isNaN(widthMax) || elText.clientWidth < widthMax) && addCss(el, { width: elText.clientWidth - 1 + "px" });
  82. }
  83. this.debug && console.info(elText.clientWidth, el.clientWidth);
  84. this.enableRoll = elText ? elText.clientWidth > el.clientWidth : false;
  85. if(this.enableRoll) {
  86. this.inter.roll = setInterval(() => {
  87. this.offset -= this.speed;
  88. if(this.offset <= -elText.clientWidth) this.offset = 0;
  89. }, 1e3 / 60);
  90. } else this.offset = 0;
  91. });
  92. },
  93. stop() {
  94. clearInterval(this.inter.roll);
  95. }
  96. }
  97. };
  98. </script>
  99. <style lang="scss" scoped>
  100. .VciTextRoll {
  101. overflow: hidden;
  102. .tr-view {
  103. flex-wrap: nowrap;
  104. .tr-text {
  105. white-space: nowrap;
  106. padding-right: 8px;
  107. }
  108. .tr-text-fill {
  109. white-space: nowrap;
  110. }
  111. }
  112. }
  113. </style>