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

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

ボタンをクリックすると、アニメーション動作で横の3本線から×に変わり、それと同時にボタンの下にスライドダウンでメニューが表示されます。この状態で再度クリックすると、アニメーション動作で元の3本線に戻ります。それと同時にメニューがスライドアップして消えます。

 最初の状態

ボタンがクリックされる前の状態です。 

f:id:develog:20161007232131p:plain

f:id:develog:20161007232256p:plain

div要素にbeforeとafterの疑似要素を設定しています。beforeで赤の線、afterで青の線を記述しています。

 

ボタンをクリックした後の状態

ボタンの線の形状が×になっていて、メニューが表示されています。

この状態で再度ボタンをクリックすると、最初の状態に戻ります。

f:id:develog:20161007232136p:plain

f:id:develog:20161007232307p:plain

ボタンがクリックされたらdiv要素にcolorクラスを設定し、ulをdisplay:noneからdisplay:blockに変えます。

 

ソース

HTML&CSS&JS

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>CSS3×jQuery アニメーション</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;
}
#box {
  margin: 100px auto 100px;;
  width: 200px;
  height: 200px;
  border-radius: 10px;
  background: white;
  position: relative;
  cursor: pointer;
}
#hum {
  width: 100px;
  height: 4px;
  background: #000;
  position: absolute;
  top: 0;
  right:0;
  bottom: 0;
  left: 0;
  margin: auto;
  transition: 0.1s linear;
}
#hum:before {
  display: block;
  content:"";
  width: 100px;
  height: 4px;
  background: red;
  position: absolute;
  top: -20px;
  right:0;
  bottom: 0;
  left: 0;
  margin: 0 auto;
  transition: 0.1s linear;
}
#hum:after {
  display: block;
  content:"";
  width: 100px;
  height: 4px;
  background: blue;
  position: absolute;
  top: 20px;
  right:0;
  bottom: 0;
  left: 0;
  margin: 0 auto;
  transition: 0.1s linear;
}
#hum.color {
  transform: rotate(90deg);
  background: transparent;
}
#hum.color:before {
  transform: rotate(-135deg);
  top: 0;
}
#hum.color:after {
  transform: rotate(-45deg);
  top: 0;
}
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 a {
  display: block;
  width: 100%;
  height: 50px;
  line-height: 50px;
  color: white;
  text-align: center;
}
ul li a:hover {
  background: #006;
  box-sizing: border-box;
  border-bottom: solid 1px white;
}
</style>
<script src="../js/jquery-2.2.4.min.js"></script>
<script>
$(function(){
  $('#box').on('click',function(){
    $('#hum').toggleClass('color');
    $('ul').slideToggle(200);
  });
});
/*
$(function(){
  $('#box').on('click',function(){
    $('#hum').toggleClass('color')

    if($('ul').css('display') == 'block'){
      $('ul:not(:animated)').slideUp('slow');
    }else{
      $('ul').slideDown('slow');
    }
  });
});
*/
</script>
</head>

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