利用js编写响应式侧边栏

为了练手,自己学敲网站时刚好碰到需要制作侧边栏,在网上也查了各种插件以及框架都可以实现这个功能,但是想自己学着用js原生学一个试试,于是就初略完成了侧边栏的实现,可以让初学者参考参考,代码能力有限。

其中主要设计的就是animate()函数,animate() 方法执行 CSS 属性集的自定义动画。该方法通过CSS样式将元素从一个状态改变为另一个状态。CSS属性值是逐渐改变的,这样就可以创建动画效果。只有数字值可创建动画(比如 "margin:30px")。字符串值无法创建动画(比如 "background-color:red")。更多的使用请自己去搜索,我就不具体介绍了。另外就是利用了媒体查询方法,通过检测当前设备的屏幕大小进行调整侧边栏的大小设计。媒体查询方法可以针对不同的屏幕尺寸设置不同的样式,特别是如果你需要设置设计响应式的页面

接下来是具体的实现,附上代码

rush:xhtml;"> <Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width,initial-scale=1"/> <a href="https://www.jb51.cc/tag/cebianlan/" target="_blank" class="keywords">侧边栏</a>
侧边栏内容
课程
退出

js实现:

rush:js;"> $(function(){

var windowWidth = $(window).width();
var windowHeight = $(window).height();
var sideBarWidth = windowWidth*0.8;
//设置侧边栏左边宽度与右边高度
$(".sideBar-left").height(windowHeight);
$(".sideBar-right").height(windowHeight);
//侧边栏由左向右滑动
$(".nav-icon").on("click",function(){
$(".sideBar").animate({left: "0"},350);
});
//点击退出侧边栏由右向左滑动
$(".exit").on("click",function(){
$(".sideBar").animate({left: "-100%"},350);
});

})

css设计:

rush:css;"> *{ margin: 0; } a{ color: #fff; text-decoration: none; } .container{ width: 100%; height: 100%; min-width: 280px; position: relative; } .header{ background: #0C7AB3; list-style: none; } .nav-icon{ width: 30px; background: #0C7AB3; padding: 8px; } .nav-icon span{ display: block; border: 1px solid #fff; margin: 4px; width: 20px; } .nav-icon:hover{ cursor: pointer; } .sideBar{ width: 100%; position: absolute; top: 0px; left: -100%; } .sideBar-left{ width: 75%; background: #fff; float: left; background-color: #343A3E; } .sideBar-left .divider{ width: 80%; height: 6px; margin-top: 30px; padding-left: 15px; background-color: #3099FF; } .sideBar-left .body-content{ width: 80%; margin-top: 15px; padding: 15px 0 15px 15px; border-top: 2px solid #3099FF; color: #EFEFEF; } .body-content .item{ margin: 4px; } .item ul{ list-style: none; margin-left: -24px; } .item ul li{ margin:8px; } .item .circle{ width: 10px; height: 10px; margin-right: 10px; border-radius: 50%; background-color: #3099FF; display: inline-block; } .sideBar-right{ width:25%; display: inline-block; background-color: rgba(0,0.5); }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...