6行程でアコーディオンメニューを導入

2012-09-08    607   1530


jQueryを使用してたった6行程でアコーディオンメニューを完成させているコードがあったのでご紹介。
$(function(){
    $("dd:not(:first-child)").css("display","none")
    $("dl dt").click(function(){
        if($("+dd",this).css("display")=="none"){
            $(this).siblings("dd").slideUp("slow");
            $("+dd",this).slideDown("slow");
        }
    });
})
このコードで注目すべきはDOMの指定方法。「not(:first-child))」「siblings」「$("+dd",this)」の3つを理解しておけば、コードを短くスッキリさせられるケースが頻繁に出てきそうです。
<html>
<head>
<!----><!----><title>アコーディオンメニュー</title>
<!----><!----><script type="text/javascript" src="jquery.js"></script>
<!----><!----><script type="text/javascript">
$(function(){
    $("dd:not(:first-child)").css("display","none")
    $("dl dt").click(function(){
        if($("+dd",this).css("display")=="none"){
            $(this).siblings("dd").slideUp("slow");
            $("+dd",this).slideDown("slow");
        }
    });
})
</script>
<!----><!----></head>
<body>
<div>
    <dl>
        <dt>タイトル1</dt>
        <dd>テキストテキストテキスト</dd>
        <dt>タイトル2</dt>
        <dd>テキストテキストテキスト</dd>
        <dt>タイトル3</dt>
        <dd>テキストテキストテキスト</dd>
    </dl>
</div>
<!----><!----></body>
</html>

参考ページ
https://ascii.jp/elem/000/000/435/435362/index-2.html

カテゴリ: jQuery

comment 登録なしでご自由にご入力いただけます(^^)ぜひぜひ記事のご感想をお聞かせ下さい。

お名前とコメントは入力必須です。

コメントの文字数が短すぎます。

この内容でコメントを送る
コメントをする

目が疲れている方向けにラジオ系Youtubeを始めました

オススメのjQueryに関する記事

この記事がお役に立てましたら是非シェアのご協力お願いします。