Last active
January 22, 2016 08:34
-
-
Save kurozumi/750ae9b4827da1c68e59 to your computer and use it in GitHub Desktop.
【jQuery】タブメニューの自動切り替えのサンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <head> | |
| <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" > | |
| <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> | |
| <script> | |
| $.fn.autoChange = function (config) { | |
| var options = $.extend({ | |
| type: 'repaet', | |
| timeout: 3000, | |
| selector: 'div.content > p' | |
| }, config); | |
| // 指定した要素の子要素を取得 | |
| var element = $(this).children(); | |
| // 要素を切り替えるスクリプト | |
| var change = function () { | |
| // selectedクラスが設定されている要素のインデックス番号を取得 | |
| var current = $(element).index($(".active")); | |
| // 次のインデックス番号を設定 | |
| var next = current + 1; | |
| // activeクラスを削除 | |
| $(element).removeClass("active"); | |
| switch(options.type) { | |
| case 'repeat': // リピートする場合 | |
| $(options.selector).hide(); | |
| if ((next + 1) > element.length) { | |
| $(element[0]).addClass("active"); | |
| $($("a", element[0]).attr('href')).show('slow'); | |
| } else { | |
| $(element[next]).addClass("active"); | |
| $($("a", element[next]).attr('href')).show('slow'); | |
| } | |
| break; | |
| case 'stop': // 最後の要素でストップする場合 | |
| if ((next + 1) > element.length) { | |
| return; | |
| } else { | |
| $(options.selector).hide(); | |
| } | |
| break; | |
| } | |
| }; | |
| // コンテンツ上ににカーソルがある場合停止 | |
| $(options.selector).hover( | |
| function () { | |
| clearInterval(timer); | |
| }, | |
| function () { | |
| timer = setInterval(function () { | |
| change(); | |
| }, options.timeout); | |
| } | |
| ); | |
| // 設定時間毎にスクリプトを実行 | |
| var timer = setInterval(function () { | |
| change(); | |
| }, options.timeout); | |
| }; | |
| // 自動切り替えする要素の設定 | |
| $(window).load(function () { | |
| $('ul.nav').autoChange({ | |
| type: 'repeat', | |
| timeout: 5000, | |
| selector: 'div.tab-content > p' | |
| }); | |
| }); | |
| </script> | |
| </head> | |
| <body> | |
| <ul class="nav nav-tabs"> | |
| <li class="active"><a href="#menu-1">111</a></li> | |
| <li><a href="#menu-2">222</a></li> | |
| <li><a href="#menu-3">333</a></li> | |
| </ul> | |
| <div class="tab-content"> | |
| <p id="menu-1" class="tab-pane active">111</p> | |
| <p id="menu-2" class="tab-pane">222</p> | |
| <p id="menu-3" class="tab-pane">333</p> | |
| </div> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment