ellipsisScroll.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <!--
  2. * @FileDescription: 文本超出显示省略号 移动鼠标上去滚动显示
  3. * @Author: 黄琪勇
  4. * @Date:2024-03-25 11:50:36
  5. -->
  6. <template>
  7. <div ref="ellipsisScrollDom" :class="[isScroll && 'isScroll', isScroll && props.autoScroll && 'autoScroll']" class="ellipsisScroll">
  8. {{ props.title }}
  9. </div>
  10. </template>
  11. <script setup lang="ts">
  12. import { ref, onMounted, onUnmounted, nextTick } from "vue"
  13. const props = defineProps<{
  14. title: string
  15. autoScroll?: boolean
  16. }>()
  17. const ellipsisScrollDom = ref<HTMLElement>()
  18. const isScroll = ref(false)
  19. onMounted(() => {
  20. if (props?.autoScroll) {
  21. nextTick(() => {
  22. handleAutoScroll(ellipsisScrollDom.value)
  23. })
  24. } else {
  25. ellipsisScrollDom.value?.addEventListener("mouseenter", handleIsScroll)
  26. ellipsisScrollDom.value?.addEventListener("mouseleave", handleLeaveScroll)
  27. }
  28. })
  29. onUnmounted(() => {
  30. if (!props?.autoScroll) {
  31. ellipsisScrollDom.value?.removeEventListener("mouseenter", handleIsScroll)
  32. ellipsisScrollDom.value?.removeEventListener("mouseleave", handleLeaveScroll)
  33. }
  34. })
  35. let widthCalc = 0
  36. function handleIsScroll(e: MouseEvent) {
  37. const target = e.target as HTMLElement
  38. widthCalc = target.scrollWidth - target.clientWidth
  39. if (widthCalc >= 0) {
  40. isScroll.value = true
  41. } else {
  42. isScroll.value = false
  43. }
  44. }
  45. function handleAutoScroll(target: any) {
  46. widthCalc = target.scrollWidth - target.clientWidth
  47. if (widthCalc >= 0) {
  48. isScroll.value = true
  49. } else {
  50. isScroll.value = false
  51. }
  52. }
  53. function handleLeaveScroll() {
  54. isScroll.value = false
  55. }
  56. </script>
  57. <style lang="scss" scoped>
  58. .ellipsisScroll {
  59. width: 99%;
  60. white-space: nowrap;
  61. text-overflow: ellipsis;
  62. overflow: hidden;
  63. @keyframes roll {
  64. 0% {
  65. transform: translateX(0);
  66. }
  67. 100% {
  68. transform: translateX(-100%);
  69. }
  70. }
  71. &.isScroll {
  72. &:hover {
  73. width: auto;
  74. overflow: initial;
  75. animation: 3s roll linear infinite normal;
  76. }
  77. }
  78. &.autoScroll {
  79. width: auto;
  80. overflow: initial;
  81. animation: 3s roll linear infinite normal;
  82. }
  83. }
  84. </style>