美文网首页CSS
实现抽屉侧边栏(主体移动)

实现抽屉侧边栏(主体移动)

作者: Hi小胡 | 来源:发表于2018-01-10 23:23 被阅读42次

    效果:

    代码:

    html:

    <div id="all">
      <div id="drawer"></div>
      <div id="main">
        <div id="nav">
          <div id="open"></div>
        </div>
        <div id="content"></div>
        <div id="mask"></div>
      </div>
    </div>
    

    css:

    #all{
      position:absolute;
      top:50%;
      left:50%;
      transform:translate(-50%,-50%);
      background:#ddd;
      width:300px;
      height:500px;
      overflow:hidden;
    }
    #drawer{
      position:absolute;
      width:200px;
      height:500px;
      background:skyblue;
      top:0;
      left:-200px;
      transition:all 0.5s;
    }
    #main{
      position:absolute;
      width:300px;
      height:500px;
      background:tomato;
      top:0;
      left:0;
      transition:all 0.5s;
    }
    #nav{
      height:50px;
      background:yellow;
      position:relative;
    }
    #open{
      background:tomato;
      width:35px;
      height:35px;
      position:absolute;
      top:50%;
      left:10px;
      transform:translate(0,-50%);
      cursor:pointer;
    }
    #mask{
      display:none;
      position:absolute;
      width:300px;
      height:500px;
      top:0;
      background:rgba(0,0,0,.5);
    }
    

    javascript:

    var drawer = document.getElementById("drawer");
    var main = document.getElementById("main");
    var mask = document.getElementById("mask");
    document.getElementById("open").onclick = function(){
      drawer.style.left = 0; 
      main.style.left = 200 + "px"; 
      mask.style.display = "block";
    }
    mask.onclick = function(){
      drawer.style.left = -200 + "px"; 
      main.style.left = 0; 
      mask.style.display = "none";
    }
    

    原理:对元素的left属性进行动态的调整,并且在主布局中利用overflow:hidden对超出部分进行隐藏

    相关文章

      网友评论

        本文标题:实现抽屉侧边栏(主体移动)

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