多くのカスタム スライダーを作成した後、これが私が使用する方法です。作成される jQuery オブジェクトの数を最小限に抑えるために、このようにしています。これは、変数によって管理されているアクティブな要素を見つけるためにテストしていないためです。$(elem:visable) や $(elem).hasClass のようなことをするのは jQuery オブジェクトの無駄です。本当に必要でない限り、jQuery を使用してアプリケーションの状態を検出するべきではありません。
//create a universal block jQuery object, and give it an index property (current)
var blocks = $('div.blocks');
blocks.current = 0;
var next = $('.next'),
prev = $('.prev');
//make a universal slide handler
function blockControl(index){
//using hide and show here to fit your example,
//but this is where you would do slide or fades or whatever animation
//the important part is it is 'showing' based on .eq()
blocks.hide().eq(index).show();
}
//setup the initial state
blockControl(blocks.current);
next.on('click', function(){
//move current up one
blocks.current ++;
//test if its the last block
if( blocks.current >= blocks.length ){
//prevent over reach
blocks.current = blocks.length;
//handle how the last slide will work, you could loop back the beginning or
//whatever. Here we are just going to hide the next button.
next.fadeOut();
prev.fadeIn();
}else{
//insure prev button is visalbe
prev.fadeIn();
//do slider
blockControl(blocks.current);
}
});
prev.on('click', function(){
//move current down one
blocks.current --;
//test if its the first block
if( blocks.current <= 0 ){
//prevent negative numbers
blocks.current = 0;
//Here we are just going to hide the prev button. But we also could put in control
//to loop the last or whatever
prev.fadeOut();
next.fadeIn();
}else{
//insure next button is visalbe
next.fadeIn();
//do slider
blockControl(blocks.current);
}
});
ここでのロジックの分離は重要です。ブロックの視覚化を制御するための単一のハンドラーがあるということは、矢印以外のものによってトリガーできることを意味します。また、矢印のロジックとコントローラーのロジックは、互いに独立して変更できます。また、テストやクエリを実行することなく、アプリケーションのどの部分からでも、現在表示されている要素にいつでもアクセスできます。
ここでの概念と、なぜそれが分離されているのかを本当に理解していることを願っています. このパターンは、ほぼすべての種類のスライダーまたはコンテンツ ローテーターに使用できます。たとえば、小さなクリック可能なブレット インジケーターが必要な場合は、簡単にフックできます。
var bullets = $('a.bullet');
bullets.on('click',function(){
var index = $(this).index();
bullets.removeClass('active').eq(index).addClass('active');
blockControl(index);
});
など。
これを OO スタイルにするとさらにクールになるので、1 ページに複数のスライダーを配置できます。しかし、それは別の話です。