设计思路:
点击按钮,CSS动画,显示侧边导航栏,再次点击,隐藏。
1、编写HTML结构与CSS动画
2、JS获取点击按钮元素和侧边栏元素。
3、给按钮元素添加onclick事件。
4、获取侧边导航栏的right的值,使用parsoInt()转换为整数。
5、if判断当前侧边栏状态,添加显示或者隐藏类名。
效果图:
HTML代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,user-scalable=no"> <title>My web</title> </head> <body> <div class="warp"> <a id="navber_btn"> Go </a> <ul id="navber_nav" style="right:-200px;" ></ul> </div> </body> </html>
CSS代码:
*{padding:0;margin:0;} #navber_btn{display:block;width:40px;height:40px;line-height:40px;text-align:center;float:right;border:1px solid #dfdfdf;} #navber_nav{position:fixed;width:200px;background:#4d5158;top:48px;height:100%;} /*显示*/ .nav-show{ -webkit-animation:nav-show 1s linear 0s alternate forwards; -moz-animation:nav-show 1s linear 0s alternate forwards; -ms-animation:nav-show 1s linear 0s alternate forwards; -o-animation:nav-show 1s linear 0s alternate forwards; animation:nav-show 1s linear 0s alternate forwards; } @keyframes nav-show{ 0% {right:-300px;} 100% {right:0px; } } @-moz-keyframes nav-show{ 0% {right:-300px;} 100% {right:0px; } } @-webkit-keyframes nav-show{ 0% {right:-300px;} 100% {right:0px; } } @-o-keyframes nav-show{ 0% {right:-300px;} 100% {right:0px; } } /*隐藏*/ .nav-hide{ -webkit-animation:nav-hide 1s linear 0s alternate forwards; -moz-animation:nav-hide 1s linear 0s alternate forwards; -ms-animation:nav-hide 1s linear 0s alternate forwards; -o-animation:nav-hide 1s linear 0s alternate forwards; animation:nav-hide 1s linear 0s alternate forwards; } @keyframes nav-hide{ 0% {right:0px; } 100% {right:-300px;} } @-moz-keyframes nav-hide{ 0% {right:0px; } 100% {right:-300px;} } @-webkit-keyframes nav-hide{ 0% {right:0px; } 100% {right:-300px;} } @-o-keyframes nav-hide{ 0% {right:0px; } 100% {right:-300px;} }
JS代码:
var navber_nav = document.getElementById('navber_nav'); var navber_btn = document.getElementById('navber_btn'); navber_btn.onclick=function(){ var dirPos = parseInt(navber_nav.style.right, 10); if (dirPos == -200) { navber_nav.style.right="0"; navber_nav.classList.add('nav-show'); navber_nav.classList.remove('nav-hide'); } else { navber_nav.style.right="-200px"; navber_nav.classList.remove('nav-show'); navber_nav.classList.add('nav-hide') } }
注:通过navber_nav.style.right
取值的元素,必须要设置position
定位属性。并且这种方式只能获取到行内样式
的属性值。