实现左右div可通过中间部分拖拽调整宽度

<div class="outside" ref="box">
  <div class="leftBox" ref="left">左边</div>
  <div class="resize" ref="resize" title="收缩侧边栏">⋮</div>
  <div class="rightBox" ref="mid">右边</div>
</div>

方法
 dragControllerDiv() {
      var resize = document.getElementsByClassName("resize");
      var left = document.getElementsByClassName("leftBox");
      var mid = document.getElementsByClassName("rightBox");
      var box = document.getElementsByClassName("outside");
      for (let i = 0; i < resize.length; i++) {
        // 鼠标按下事件
        resize[i].onmousedown = function (e) {
          //颜色改变提醒
          resize[i].style.background = "#818181";
          var startX = e.clientX;
          resize[i].left = resize[i].offsetLeft;
          // 鼠标拖动事件
          document.onmousemove = function (e) {
            var endX = e.clientX;
            var moveLen = resize[i].left + (endX - startX); // (endx-startx)=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
            var maxT = box[i].clientWidth - resize[i].offsetWidth; // 容器宽度 - 左边区域的宽度 = 右边区域的宽度

            if (moveLen < 32) moveLen = 32; // 左边区域的最小宽度为32px
            if (moveLen > maxT - 150) moveLen = maxT - 150; //右边区域最小宽度为150px

            resize[i].style.left = moveLen; // 设置左侧区域的宽度

            for (let j = 0; j < left.length; j++) {
              left[j].style.width = moveLen + "px";
              mid[j].style.width = box[i].clientWidth - moveLen - 10 + "px";
            }
          };
          // 鼠标松开事件
          document.onmouseup = function (evt) {
            //颜色恢复
            resize[i].style.background = "#d6d6d6";
            document.onmousemove = null;
            document.onmouseup = null;
            resize[i].releaseCapture && resize[i].releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          };
          resize[i].setCapture && resize[i].setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false;
        };
      }
    },

css
.outside {
  width: 100%;
  display: flex;
  // height: 100%;
  height: calc(100vh - 100px) !important;
  margin: 1% 0px;
  overflow: hidden;
  background: #eaeef2;
/*拖拽区div样式*/
.resize {
  cursor: col-resize;
  float: left;
  position: relative;
  top: 45%;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: center;
  /*z-index: 99999;*/
  font-size: 32px;
  color: white;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
  color: #444444;
}
  .leftBox {
    width: calc(18% - 20px); /*左侧初始化宽度*/
    height: calc(100vh - 100px);
    background: #fff;
    padding: 0 0 10px;
    margin: 10px 0 10px 10px;
    overflow: auto;
    }
 .rightBox {
    // float: left;
    width: 82%; /*右侧初始化宽度*/
    height: 100%;
    flex: 1;    
    background: #fff;
    margin: 10px 10px 10px 0;
    overflow: auto;
}
  }



猜你喜欢

转载自blog.csdn.net/qq_44716001/article/details/132048210
今日推荐