CSS实现侧边栏滑进滑出功能
程序员文章站
2022-07-03 20:14:12
效果
用的csdn做的例子, 本篇博客主要讲的是侧边栏滑进滑出, 背景是图片……, 不要在意.
代码
//index.html
<...
效果
用的csdn做的例子, 本篇博客主要讲的是侧边栏滑进滑出, 背景是图片……, 不要在意.
代码//index.html <!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"> <title>home</title> <script> var documentElement = document.documentElement; //获取html元素 documentElement.style.fontSize = documentElement.getBoundingClientRect().width / 16 + 'px'; //设置为视窗宽度的1/16 </script> <link rel="stylesheet" type="text/css" href="./index.css"> </head> <body> <!-- 网页主体容器 --> <p class="body"> <!-- 左上角头像 --> <a href="javascript:void(0)" class="avatar-small"></a> <!-- 方便演示内容图片代替主页 --> <img class="main" src="./img/1.PNG"> </p> <!-- 网页遮罩 --> <p class="mask"></p> <!-- 侧边栏 --> <p class="nav"> <ul> <li> <a> <img src="./img/avatar.jpg" class="avatar-big" alt=""> </a> </li> <li> <a>我的课程</a> </li> <li> <a>我的订单</a> </li> <li> <a>我的收藏</a> </li> <li> <a>个人中心</a> </li> </ul> </p> <script type="text/javascript" src="./index.js"></script> </body> </html>
//index.css body { margin: 0; } ul, li { list-style: none; padding: 0; margin: 0; } .avatar-small { position: absolute; z-index: 2; left: 0; top: 0; width: 2rem; height: 2rem; } .main{ width: 100vw; height: 100vh; } .mask { display: none; position: fixed; z-index: 10; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, .1); } .nav { position: absolute; z-index: 11; left: -7rem; top: 0; width: 7rem; height: 100%; background: #555; } .nav { transition: left linear .1s; } .nav a { display: block; padding: 1em 0; border-bottom: 1px solid #888; font-size: 16px; color: #eee; text-align: center; } .nav .avatar-big { width: 3rem; border-radius: 50%; box-shadow: 0 6px 12px rgba(0, 0, 0, .175); }
//index.js let btn = document.getElementsByClassName('avatar-small')[0], mask = document.getElementsByClassName('mask')[0], nav = document.getElementsByClassName('nav')[0]; btn.addEventListener('click', function () { mask.style.display = 'block'; nav.style.left = 0; }, false); mask.addEventListener('click', function () { mask.style.display = 'none'; nav.style.left = '-7rem'; }, false)