利用js编写响应式侧边栏

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

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

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

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设计: 

*{
 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, 0, 0.5);
}

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

你可能感兴趣的:(利用js编写响应式侧边栏)