vue实现拖拽修改【当前元素宽度】

上篇博客分享了修改左右两侧元素的宽度【vue实现拖拽修改左右两侧元素宽度】,在实践中还会遇到仅修改某一单一元素宽度,以下是实现方法:

实现效果

在这里插入图片描述

HTML

<div class="container">
  测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试
  <div ref="containerDom" class="right">
    <div style="display: flex; height: 100%">
      <div class="resize" ref="resizeDom"></div>
      <div style="flex: 1">右侧测试</div>
    </div>
  </div>
</div>

实现方法

dragControllerDiv() {
  const resizeDom = this.$refs.resizeDom;
  const containerDom = this.$refs.containerDom;
  resizeDom.style.cursor = "e-resize";
  resizeDom.onmousedown = (e) => {
    document.onselectstart = function () {
      return false;
    }; //解决拖动会选中文字的问题
    // 鼠标按下,计算当前元素距离可视区的距离
    const disX = e.clientX;
    const w = containerDom.clientWidth;
    const minW = 300;
    const maxW = 1800;
    var nw;
    document.onmousemove = (e) => {
      // 通过事件委托,计算移动的距离
      const l = e.clientX - disX;
      // 改变当前元素宽度,不可超过最小最大值
      nw = w - l;
      nw = nw < minW ? minW : nw;
      nw = nw > maxW ? maxW : nw;
      containerDom.style.width = `${nw}px`;
    };

    document.onmouseup = (e) => {
      document.onmousemove = null;
      document.onmouseup = null;
    };
  };
}

CSS

.container {
  position: relative;
}
.resize {
  cursor: col-resize;
  position: relative;
  top: 45%;
  left: -15px;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: center;
  font-size: 32px;
  color: white;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
  color: #444444;
}
.right {
  width: 400px;
  height: 100vh;
  border: 1px solid #ccc;
  position: fixed;
  top: 0;
  right: 0;
  box-shadow: 4px 4px 2px 8px #f5f5f5;
  background: #fff;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值