index.vue 1.9 KB
Newer Older
P
Pan 已提交
1
<template>
P
Pan 已提交
2 3
  <div class="scroll-container" ref="scrollContainer" @mousewheel="handleScroll">
    <div class="scroll-wrapper" ref="scrollWrapper" :style="{left: left + 'px'}">
P
Pan 已提交
4 5 6 7 8 9
      <slot></slot>
    </div>
  </div>
</template>

<script>
P
Pan 已提交
10 11
const padding = 15 // tag's padding

P
Pan 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25
export default {
  name: 'scrollPane',
  data() {
    return {
      left: 0
    }
  },
  methods: {
    handleScroll(e) {
      e.preventDefault()
      const $container = this.$refs.scrollContainer
      const $containerWidth = $container.offsetWidth
      const $wrapper = this.$refs.scrollWrapper
      const $wrapperWidth = $wrapper.offsetWidth
P
Pan 已提交
26

P
Pan 已提交
27 28 29
      if (e.wheelDelta > 0) {
        this.left = Math.min(0, this.left + e.wheelDelta)
      } else {
P
Pan 已提交
30 31
        if ($containerWidth - padding < $wrapperWidth) {
          if (this.left < -($wrapperWidth - $containerWidth + padding)) {
P
Pan 已提交
32 33
            this.left = this.left
          } else {
P
Pan 已提交
34
            this.left = Math.max(this.left + e.wheelDelta, $containerWidth - $wrapperWidth - padding)
P
Pan 已提交
35 36 37 38 39
          }
        } else {
          this.left = 0
        }
      }
P
Pan 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
    },
    moveToTarget($target) {
      const $container = this.$refs.scrollContainer
      const $containerWidth = $container.offsetWidth
      const $targetLeft = $target.offsetLeft
      const $targetWidth = $target.offsetWidth

      if ($targetLeft < -this.left) {
        // tag in the left
        this.left = -$targetLeft + padding
      } else if ($targetLeft + padding > -this.left && $targetLeft + $targetWidth < -this.left + $containerWidth - padding) {
        // tag in the current view
        // eslint-disable-line
      } else {
        // tag in the right
        this.left = -($targetLeft - ($containerWidth - $targetWidth) + padding)
      }
P
Pan 已提交
57 58 59 60 61 62 63 64 65
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.scroll-container {
  white-space: nowrap;
  position: relative;
P
Pan 已提交
66
  overflow: hidden;
P
Pan 已提交
67 68 69 70 71
  .scroll-wrapper {
    position: absolute;
  }
}
</style>