How can I resize a DIV by dragging just ONE side of it?

前端 未结 9 2249
后悔当初
后悔当初 2020-12-12 17:38

Let me be more specific... I don\'t want the DIV to resize WHILE I\'m dragging. I want to drag it out (and maybe a vertical line follows my cursor) and when I release, it re

9条回答
  •  Happy的楠姐
    2020-12-12 17:52

    Pure JS
    Live Update
    CSS Variable

    let dragging = 0,
      body = document.body,
      target = document.getElementById('dragbar');
    
    function clearJSEvents() {
      dragging = 0;
      body.removeEventListener("mousemove", resize);
      body.classList.remove('resizing');
    }
    
    function resize(e) {
      if (e.pageX > 400 || e.pageX < 200) {
        return;
      }
      body.style.setProperty("--left-width", e.pageX + 'px');
    }
    
    target.onmousedown = function(e) {
      e.preventDefault();
      dragging = 1;
      body.addEventListener('mousemove', resize);
      body.classList.add('resizing');
    };
    
    document.onmouseup = function() {
      dragging ? clearJSEvents() : '';
    };
    body {
      --left-width: 300px;
      padding: 0;
      margin: 0;
    }
    
    body.resizing {
      cursor: col-resize;
    }
    
    #main,
    #sidebar,
    #dragbar {
      top: 0;
      height: 100%;
      background: white;
      position: absolute;
    }
    
    #sidebar {
      background: #e6e9f0;
      width: var(--left-width);
    }
    
    #main {
      right: 0;
      overflow: scroll;
      width: calc(100% - var(--left-width));
    }
    
    #main section {
      margin: 20px auto;
      border-radius: 10px;
      background: white;
      height: 100px;
      width: calc(100% - 60px);
      transition: 0.3s ease-in-out 0s;
      box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1);
    }
    
    #main section:hover {
      box-shadow: 0px 3px 25px rgba(0, 0, 0, 0.2), 0px 0px 0px 1px #A8D1FD;
    }
    
    #dragbar {
      right: 0;
      width: 5px;
      opacity: 0;
      cursor: col-resize;
      background: #0099e5;
      transition: 0.3s ease-in-out 0s, opacity 0.3s ease-in-out 0s;
    }
    
    #dragbar:hover,
    body.resizing #dragbar {
      opacity: 1;
      transition: 0.3s ease-in-out 0s, opacity 0.3s ease-in-out .3s;
    }
    
      
      

提交回复
热议问题