先看利用animation属性制作侧边栏淡入淡出的最终效果:
html代码:
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>侧边栏隐藏效果</title> </head> <body> <div> <div class='sidebar '>sidebar</div> <div> <div> <button οnclick="fadeIn()">淡进</button> <button οnclick="fadeOut()">淡出</button> </div> </div> </div> </body> </html>
css代码:
<style type="text/css"> *{ margin:0;padding:0; } .move_right { animation: move_right 1s forwards; } @keyframes move_right { from {opacity: 0;transform: translateX(0px);} to { opacity: 1; transform: translateX(150px); } } .move_left { animation: move_left 1s forwards; } @keyframes move_left { from {opacity: 1;transform: translateX(0px);} to { opacity: 0; transform: translateX(-150px); } } .container{ position:relative; padding-top:500px; } .sidebar{ position:absolute; background:orange; height:500px; width:120px; left:0px; top:0px; } </style>
这里还用到了一点javascript,如下:
<script> var sidebarEl = document.querySelector(".sidebar"); function fadeIn (e) { sidebarEl.className = 'sidebar'; sidebarEl.style.top = '0px'; sidebarEl.style.left = '-150px'; sidebarEl.classList.add('move_right'); } function fadeOut (e) { sidebarEl.className = 'sidebar'; sidebarEl.style.left = '0px'; sidebarEl.style.top = '0px'; sidebarEl.classList.add('move_left'); } </script>
总结:
这里使用了一点js来给按钮增加点击事件