4

需求:拖动实现改变左右宽度
实现效果:
9p3z0-kt94e.gif

实现步骤:
1.代码

 <div class="box" ref="box">
    <div class='left'>左侧</div>
    <div class="resize" title="收缩侧边栏">
        ⋮
    </div>
    <div class='right'>右侧</div>
</div>

2.样式

.left {
    width: 49.2%;
    height:100%;
    overflow-y:auto;
    overflow-x:hidden;
    float: left;
}
.resize {
    cursor: col-resize;
    float: left;
    position: relative;
    top: 45%;
    background-color: #d6d6d6;
    border-radius: 5px;
    width: 0.6%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-size: cover;
    background-position: center;
    font-size: 0.32rem;
    color: white;
}
/*拖拽区鼠标悬停样式*/
.resize:hover {
    color: #444444;
}
.right {
    height:7.8rem;
    float: left;
    width:50%;
}
.box {
    width: 100%;
    height: 7.8rem;
}

3.方法

dragControllerDiv: function () {
    var resize = document.getElementsByClassName('resize');
    var left = document.getElementsByClassName('left');
    var mid = document.getElementsByClassName('right');
    var box = document.getElementsByClassName('box');
    for (let i = 0; i < resize.length; i++) {
        // 鼠标按下事件
        resize[i].onmousedown = function (e) {
            //颜色改变提醒
            resize[i].style.background = '#818181';
            var startX = e.clientX;
            // 鼠标拖动事件
            document.onmousemove = function (e) {
                resize[i].left = startX;
                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/document.body.clientWidth)*100 + '%';
                    mid[j].style.width = ((box[i].clientWidth - moveLen)/document.body.clientWidth - 0.008)*100 + '%';
                }
            };
            // 鼠标松开事件
            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;
        };
    }
},

4.实现

mounted: function () {
    let me=this;
    me.dragControllerDiv();
}

参考文章:https://www.cnblogs.com/ingri...
将不断更新完善,期待您的批评指正!


薇薇
298 声望24 粉丝

路漫漫其修远兮,吾将上下而求索