懐しのlightboxのように、モーダル間を左右で移動させる。
動作フロー&簡単な注釈
左右移動ボタン
- クリックされた要素の親の親要素を取得
- bodyを非表示
- クリックされた要素のclassがnext,prevどちらかを判定
- それによって親の親要素の前後どちらかのモーダルを呼び出す
※モーダルが重なるとスクロール2重に表示されてしまうので、2の処理をしている。
閉じるボタン
- 「閉じる」がクリックされたら
- 連番で付けたモーダルIDの数だけモーダルを閉じる
- bodyの要素を表示させる
※上記の動作によって、複数のモーダルが開かれている可能性があるので、全てのモーダルを閉じています。
コード
呼び出しボタン
BootstrapのExampleままでOK。
下記はhrefで呼び出しているが、data-targetでも可。(だと思う)
<a href="#portfolioModal1" data-toggle="modal">
</a>
modal側コード
これもほぼexampleままで可。
閉じるボタンの他に、前後への移動ボタンを下記のように記載しておく。modal-move,prev,nextはjQueryでの呼び出しでも使うので、変更する際は、jQuery側も一緒に行うこと。
<div class="modal fade" id="Modal1" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-content">
<div class="close">閉じる</div>
<div class="modal-move prev">前へ</div>
<div class="modal-move next">次へ</div>
<div class="modal-body">本文</div>
</div>
</div>
js
// [[[[[[[[ 関数定義 ]]]]]]]] //
function moveBtn(directionStr){
$('.modal-move.'+directionStr).click(function() {
// ボタンの親要素を取得
var parentsModal = $(this).parents("div.modal");
// 親要素モーダルを非表示
$(parentsModal).modal('hide');
// 親要素に隣接したmodalを取得して表示
// モーダル時にスクロールバーを非表示にする
$(document.body).css({overflow: 'hidden'});
// 引数の要素によって、前と次どちらをを表示するかを判定
if ("prev" === directionStr) {
parentsModal.prev().modal('show');
}
else if ("next" === directionStr){
parentsModal.next().modal('show');
}
else{
console.log("Args is not much direction ")
};
});
}
// [[[[[[[[ 実行部分 ]]]]]]]] //
// モーダルの前次ボタン
moveBtn("prev")
moveBtn("next")
// modal全部閉じる
$('.close').click(function(){
for (var i = 1; i < 7; i++) {
$("#Modal"+i).modal('hide');
};
$(document.body).css({overflow: 'visible'});
});