Scroll.vue 2.01 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
<!--
 * @Author: your name
 * @Date: 2022-04-12 16:09:32
 * @LastEditTime: 2022-04-13 15:41:17
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /gassafety-progress/gassafetyprogress-web/src/components/scrollCom/scroll.vue
-->
<template>
  <div
    class="scroll"
    @mouseover="stopScroll"
    @mouseout="startScroll"
    ref="wrapper"
  >
    <div ref="scroll" :style="{ top: pxTop }" class="contain">
      <slot :dataList="dataList" />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    dataList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      timer: null,
      top: 0,
      wrapperHeight: 0,
      scrollHeight: 0,
    };
  },
  computed: {
    pxTop() {
      return this.top + "px";
    },
  },

  mounted() {
    this.init();
  },
  watch: {
    dataList: {
      handler: function (val, oldVal) {
        this.top = 0;
        this.init();
      },
      deep: true,
    },
  },
  methods: {
    init() {
      clearInterval(this.timer);
      const { height: wrapperHeight } =
        this.$refs.wrapper.getBoundingClientRect();
      const { height: scrollHeight } =
        this.$refs.scroll.getBoundingClientRect();
      this.scrollHeight = scrollHeight;
      const maxTop = wrapperHeight - scrollHeight;

      // 如果没有超过,就不滚动了
      if (maxTop > 0) return;
      this.timer = setInterval(() => {
        // this.top = this.top-1;
        this.top = this.top - 0.5;
        if (this.top <= maxTop) {
          this.top = 0;
        }
      }, 24);
    },
    stopScroll() {
      clearInterval(this.timer);
    },
    startScroll() {
      this.init();
    },
  },

  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style lang="scss" scoped>
.scroll {
  height: 100%;
  // background: red;
  overflow: hidden;
  position: relative;
}
.contain {
  width: 100%;
  position: absolute;
}
</style>