美文网首页JavaScript基础
实现左右可拖动改变宽度的div内容显示区,并且控制拖动范围

实现左右可拖动改变宽度的div内容显示区,并且控制拖动范围

作者: Hi小胡 | 来源:发表于2018-01-14 00:45 被阅读1177次

    效果:

    代码:

    html:

    <div id="box">
      <div id="left"></div>
      <div id="resize"></div>
      <div id="right"></div>
    </div>
    

    css:

    body,html{
      margin:0;
      padding:0;
      height:100%;
    }
    #box{
      width:600px;
      height:500px;
      overflow:hidden;
    }
    #left{
      width:calc(30% - 5px);
      height:100%;  
      background:skyblue;
      float:left;
    }
    
    #resize{
      width:5px;
      height:100%;
      cursor: w-resize;
      float:left;
    }
    
    #right{
      float:right;
      width:70%;
      height:100%;  
      background:tomato;
    }
    

    javascript:

    window.onload = function(){
      var resize = document.getElementById("resize");
      var left = document.getElementById("left");
      var right = document.getElementById("right");
      var box = document.getElementById("box");
      resize.onmousedown = function(e){
        var startX = e.clientX;
        resize.left = resize.offsetLeft;
        document.onmousemove = function(e){
          var endX = e.clientX;
    
          var moveLen = resize.left + (endX - startX);
          var maxT = box.clientWidth - resize.offsetWidth;
          if(moveLen<150) moveLen = 150; 
          if(moveLen>maxT-150) moveLen = maxT-150;
    
          resize.style.left = moveLen;
          left.style.width = moveLen + "px";
          right.style.width = (box.clientWidth - moveLen - 5) + "px";
        }
        document.onmouseup = function(evt){
          document.onmousemove = null;
          document.onmouseup = null; 
          resize.releaseCapture && resize.releaseCapture();
        }
        resize.setCapture && resize.setCapture();
        return false;
      }
    }
    

    相关文章

      网友评论

        本文标题:实现左右可拖动改变宽度的div内容显示区,并且控制拖动范围

        本文链接:https://www.haomeiwen.com/subject/hcnhoxtx.html