beka
5/7/2019 - 3:05 PM

分割窗口

<template>
  <div class="splitPane" ref="outer">
    <div class="pane pane-left" :style="{width: computedLeft}"></div>
    <div class="handle" @mousedown="mousedown" :style="{left: computedHandle, width: handleWidth + 'px'}"></div>
    <div class="pane pane-right" :style="{left: computedLeft}"></div>
  </div>
</template>

<script>
export default {
  name: 'splitPane',
  data() {
    return {
      offsetLeft: 0.3,
      handleWidth: 8,
      outerLeft: 0,
      isDrag: false,
      initOffset: 0,
      min: 0.1,
      max: 0.9
    };
  },
  mounted() {
  },
  computed: {
    computedLeft() {
      return `${this.offsetLeft * 100}%`
    },
    computedHandle() {
      return `calc(${this.offsetLeft * 100}% - ${this.handleWidth / 2}px)`
    }
  },
  methods: {
    mousedown(event) {
      this.isDrag = true
      this.outerLeft = this.$refs.outer.getBoundingClientRect().left
      // 按下鼠标的时候拖动条初始的偏移量(left都是相对拖动条的左边界来说的)
      this.initOffset = event.clientX - event.srcElement.getBoundingClientRect().left
      document.addEventListener('mousemove', this.mousemove)
      document.addEventListener('mouseup', this.mouseup)
    },
    mousemove(event) {
      if (!this.isDrag) return
      let left = event.clientX
      let tempOffsetLeft = (left - this.initOffset +  this.handleWidth/ 2 - this.outerLeft) / 300
      if (tempOffsetLeft >= this.min && tempOffsetLeft <= this.max) {
        this.offsetLeft = tempOffsetLeft
      }
    },
    mouseup(event) {
      this.isDrag = false
    }
}
}

</script>
<style lang='scss' scoped>
.splitPane {
  width: 300px;
  height: 130px;
  position: relative;
  .pane {
    position: absolute;
    top: 0;
    height: 100%;
    &-left {
      left: 0;
      background-color:  #de7187;
    }
    &-right {
      right: 0;
      background-color:  #a1e4ed;
    }
  }
  .handle {
    position: absolute;
    z-index: 2;
    top: 0;
    height: 100%;
    background-color: green;
    user-select: none;
    cursor: col-resize;
  }
}
</style>