美文网首页
div拖动改变大小 (横向)

div拖动改变大小 (横向)

作者: TouchMe丶 | 来源:发表于2019-03-20 09:50 被阅读0次

    转自网络

    <!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">
      <link rel="stylesheet" href="./index.css">
      <title>递归</title>
    </head>
    <body>
      <div id="box">
        <div id="left"></div>
        <div id="resize"></div>
        <div id="right"></div>
      </div>
    <script src="./index.js"></script>
    </body>
    </html>
    
    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: e-resize;
      float:left;
    }
    
    #right{
      float:right;
      width:70%;
      height:100%;  
      background:tomato;
    }
    
    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){ //resize的 onmousedown
        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; //必须大于150
          if(moveLen>maxT-150) moveLen = maxT-150; //必须小于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/nwiamqtx.html