LoginSignup
6
8

More than 5 years have passed since last update.

jQueryでスマホ向けドロップダウンメニューを作る

Last updated at Posted at 2016-04-02

はじめに

スマホでよく見るようなドロップダウンメニューを作る。
jQueryを使えば簡単に実装することができる。

HTML

以下のコードを<head>に書いてjQueryを読み込む

head
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

<header>は画面上部に表示されるメニューバー、<header>内部の<nav>がドロップダウンメニューの中身になる。
<ul>がメニューのリスト。<li>がそれぞれのメニューを示している。
#menu_buttonを押すと<ul>が開閉するように実装する。
<main>はメインコンテンツを示す。

body
<header>
    <div class="menu_button"><span>menu</span></div>
    <nav class="nav">
        <ul>
            <li>メニュー1</li>
            <li>メニュー2</li>
            <li>メニュー3</li>
        </ul>
    </nav>
</header>
<main>
    <div style="width: 50%; height:1000px; background-color: #aaa; margin: 0 auto;">
        メイン
    </div>
</main>

メニューの基本構造

<hearder>の高さを定めてその分だけ<nav><main>を下に配置する。
以下の例ではheightを40pxにしている。
<nav><main>positionをabsoluteに設定して、topをそれぞれ100%, 40pxとした。
<nav><header>の内部にあるので100%と設定すれば<header>の下に配置される。
また常にメニューバーを表示させるためにpositionをfixed、z-indexを大きな値である1000にしている。

基本構造
header {
    height: 40px;
    z-index: 1000;
    position: fixed;
}
header nav {
    position: absolute;
    top: 100%;
}
main {
    position: absolute;
    top: 40px;
}

デザイン

デザインは以下のとおり。
これでドロップダウンメニューが開かれた状態が表示される。

デザイン
header {
    background-color: #111;
    color: white;
    width: 100%;
}
header .menu_button {
    border-left: solid 1px white;
    float: right;
    width: 70px;
    height: 100%;
    text-align: center;
}
header .menu_button span {
    line-height: 40px;
}
header nav {
    background-color: #111;
    color: white;
    width: 100%;
}
header nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
header nav ul li:first-child {
    border-top: solid 1px white;
}
header nav ul li {
    border-bottom: dotted 1px white;
    text-align: center;
    padding: 1em;
}
main {
    width: 100%;
}

jQueryによるドロップダウンの実装

初期設定として.navdisplayをnoneにしてメニューが閉じた状態にする。
.menu_buttonのクリック時に$(".nav").slideToggle()が実行されるようにして完成

ドロップダウン
$(function() {
    $(".nav").css("display","none");
    $(".menu_button").on("click", function() {
        $(".nav").slideToggle();
    });
});
6
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8