原生实现可调节侧栏

73 阅读1分钟

原生实现可调节侧栏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <style>
        html,body {
            height: 100%;
            margin: 0px;
            padding: 0px;
        }
        .app {
            height: 100%;
            display: flex;
            user-select: none;
        }
        .leftBox {
            background-color: seagreen;
            min-width: 200px;
            position: relative;
        }
        .content {
            padding: 20px;
        }
        .content img  {
            display: block;
            width: 100%;
            max-height: calc(100vh - 50px);
            margin: 0 auto;
        }
        .drag {
            width: 12px;
            height: 100%;
            background-color: aliceblue;
            position: absolute;
            right: 0px;
            top: 0px;
            cursor: col-resize;
        }
        .rightBox {
            flex: 1;
            background-color: aqua;
            min-width: 200px;
        }
    </style>
 
    <div class="app">
        <div class="leftBox">
            <div class="content">
                <img src="http://img.duoziwang.com/2018/06/2018010130213237.jpg" alt="">
            </div>
            <div class="drag"></div>
        </div>
        <div class="rightBox"></div>
    </div>
 
    <script>
        function Drag() {
            this.drag_el = document.querySelector('.drag')
            this.leftBox_el = document.querySelector('.leftBox')
            this.leftBox_el_width = '200px'
            this.moveDistance_fn = null
        }
        Drag.prototype.updata = function(leftBox_el_width = '200px') {
            this.leftBox_el_width = leftBox_el_width
        }
        Drag.prototype.init = function() {
            this.updata(JSON.parse(localStorage.getItem('left_width')))
            this.leftBox_el.style.width = this.leftBox_el_width
            this.drag_el.addEventListener('mousedown', this.move.bind(this))
            document.addEventListener('mouseup', this.removeEvent.bind(this))
        }
        Drag.prototype.move = function(e) {
            document.addEventListener('mousemove', this.moveDistance(this))
        }
        Drag.prototype.removeEvent = function() {
            document.removeEventListener('mousemove', this.moveDistance_fn)
        }
        Drag.prototype.moveDistance = function(that) {
             this.moveDistance_fn = function moveDistance_fn(e) {
                that.leftBox_el.style.width = e.clientX+ 'px'
                that.leftBox_el_width = localStorage.setItem('left_width', JSON.stringify(that.leftBox_el.style.width))
            }
            return this.moveDistance_fn
        }
        new Drag().init() 
    </script>
</body>
</html>