ハンバーガーメニューを作成する

ハンバーガーメニューの動作

プラス(+)の状態のボタンをクリックすると、アニメーション動作でマイナス(-)になり、それと同時にボタンの下にスライドダウンでメニューが表示されます。マイナス(-)の状態でクリックすると、アニメーション動作でプラス(+)になります。それと同時にメニューがスライドアップして消えます。

動作画面

最初の状態

f:id:develog:20161006234331p:plain

 

ボタンをクリックした後の画面

ボタンの+が-に変わり、メニューが表示されています。

再度ボタンをクリックすると、最初の画面に戻ります。

f:id:develog:20161006234457p:plain

ソース

HTML&CSSjQuery

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>ハンバーガーメニュー</title>
<style>
html,body,ul,li,p {
  margin: 0;
  padding: 0;
  line-height: 1.0;
}
body {
  background: #06F;
}
a {
  text-decoration: none;
}
ul {
 list-style: none;
}
div#box {
  width: 100px;
  height: 100px;
  background: #222;
  margin: 100px auto 100px;
  position: relative;
  cursor: pointer;
}
p {
  width: 50px;
  height: 4px;
  background: white;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  transition: 0.2s;
}
p:before {
  display: block;
  content:"";
  width: 50px;
  height: 4px;
  background: white;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  transform: rotate(90deg);
  transition: 0.2s;
}
p.minus {
  background: transparent;
}
p.minus:before {
  transform:rotate(0deg);
}
ul {
  width: 100%;
  height: 200px;
  background: #000;
  display: none;
}
ul li {
  width: 100%;
  height: 50px;
  background: #555;
  box-sizing: border-box;
  border-bottom: solid 1px white;
}
ul li:last-child {
border-bottom: none;
}
ul li a {
  display: block;
  width: 100%;
  height: 50px;
  line-height: 50px;
  color: white;
  text-align: center;
}
ul li a:hover {
  background: #006;
  border-bottom: solid 1px white;
  box-sizing: border-box;
}
ul li:last-child a:hover {
  border-bottom: none;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
  $('#box').on('click',function(){
    $('p').toggleClass('minus');
    $('ul').slideToggle(200);
  });
});
</script>
</head>

<body>
<div id="box">
<p></p>
</div>
<ul>
<li><a href="#">ホーム</a></li>
<li><a href="#">メニュー</a></li>
<li><a href="#">お店について</a></li>
<li><a href="#">アクセス</a></li>
</ul>
</body>
</html>