2021.10.14 左右布局分割线拖拽 自适应宽度

项目需求:页面左右布局,需要拖拽分割线,实现宽度自动适应。
解决方案:在mounted生命周期,监听分割线DOM的onmousedown事件,在拖拽过程中动态计算,然后赋值改变左右DOM元素的宽度。

<template>
  <div class="wrap">
    <div class="lf" ref="letfDom"  :style="{width: curWidth}">
      <router-link to="/moreClick">moreClick</router-link>
      <div class="touch-div" ref="moveDom"> </div>
    </div>
    <div class="rt" :style="{width: curRightWidth}">
      <router-view />
    </div>
  </div>
</template>
export default {
  name: "App",
  data() {
    return {
      leftDom: null,
      clientStartX: 0,
      curWidth: '280px',
      curRightWidth: 0,
    };
  },
  mounted() {
    const wrap = this.$refs.wrap;
    const wrapWidth = wrap.clientWidth
    this.leftDom = this.$refs.leftDom;
    const leftWidth = this.leftDom.clientWidth
    let moveDom = this.$refs.moveDom;
    this.curRightWidth = wrapWidth - leftWidth + "px"
    moveDom.onmousedown = e => {
      this.clientStartX = e.clientX;
      e.preventDefault();

      document.onmousemove = e => {
        this.moveHandle(e.clientX, this.leftDom);
      };

      document.onmouseup = e => {
        document.onmouseup = null;
        document.onmousemove = null;
      };
    };
  },
  methods: {
	moveHandle(nowClientX, leftDom) {
	      const wrap = this.$refs.wrap;
	      const wrapWidth = wrap.clientWidth
	      // 左边
	      let computedX = nowClientX - this.clientStartX;
	      let leftBoxWidth = parseInt(leftDom.style.width);
	      let changeWidth = leftBoxWidth + computedX;
	      if (changeWidth < 150) {
	        changeWidth = 150;
	      }
	
	      if (changeWidth > 400) {
	        changeWidth = 400;
	      }
	
	      this.curWidth = changeWidth + "px";
	      
	      // 右边
	      this.curRightWidth = wrapWidth - changeWidth + "px"
	      
         // 刷新起点
		  this.clientStartX = nowClientX
	    },
  }
}
<style lang="scss" scoped>
.wrap{
  display: flex;
  height: 100%;
  .lf{
    height: 100%;
    display: flex;
    align-items: stretch;
    .treeWrap{
      width: calc(100% - 12px);
    }
    .touch-div{
      height: 100%;
      width: 1px;
      cursor: col-resize;
      margin-left: 10px;
      border-right: 1px solid #DCDFE6;
    }
  }
  .rf{
    padding-left: 10px;
  }
}
</style>

参考文献

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值