1. 程式人生 > >js實現可拖動的佈局

js實現可拖動的佈局

思路:採用flex佈局,js即時修改固定列的寬度

注意:父元素需設定position:relative;因offsetLeft和offsetTop是相對於具有定位的(position:absolute或者position:relative)父級元素的距離

html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"
> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="./index.css"> <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.css"> <script src="./index.js"></script
> </head> <body> <div id="box"> <div id="left"> </div> <div id="line"> <a id="line1"> <span><i class="fa fa-caret-right"></i></span> </a> </div> <
div id="right"> </div> </div> </body> </html>

css:

body {
    font: 14px/1.5 Arial;
    color: #666;
}

#box {
    position: relative;
    width: 600px;
    height: 400px;
    border: 2px solid #000;
    margin: 10px auto;
    overflow: hidden;
    display: flex;
}

#left {
    height: 100%;
    flex: 1;
    overflow: hidden;
}

#right {
    width: 300px;
    overflow: hidden;
}

#line {
    width: 8px;
    background: lightblue;
    cursor: col-resize;
}

#line a{
    cursor: pointer;
    text-align: center;
}

js:

function $(id) {
    return document.getElementById(id)
}
window.onload = function () {
    var oBox = $("box"),
        oLeft = $("left"),
        oRight = $("right"),
        oLine = $("line"),
        oLine1 = $("line1");
    var flag = true;
    var wid = 0;

    oLine.onmousedown = function (e) {
        var disX = (e || event).clientX;
        var owidth = oBox.clientWidth - oLine.offsetLeft;
        document.onmousemove = function (e) {
            var iT = owidth - ((e || event).clientX - disX);
            var e = e || window.event;
            var maxT = oBox.clientWidth - oLine.offsetWidth;
            oLine.style.margin = 0;
            iT < 30 && (iT = 30);
            iT > maxT && (iT = maxT);
            wid = iT;
            oRight.style.width = iT + "px";
            return false
        };
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
            oLine.releaseCapture && oLine.releaseCapture()
        };
        oLine.setCapture && oLine.setCapture();
        return false
    };

    oLine1.onclick = function () {
        if (flag) {
            oRight.style.width =  30 + "px";
            flag = false;
        } else {
            if (wid && wid > 30) {
                oRight.style.width = wid + "px";
            } else {
                oRight.style.width = 300 + "px";
            }
            flag = true;
        }
    }

};

 效果如下: