2016-04-27 12 views
0

ここにはa link!私が作成したスライダーにonclickスライド機能付きjQueryスライダの作成

/* Create an array to hold the different image positions */ 
var itemPositions = []; 
var numberOfItems = $('#scroller .item').length; 

/* Assign each array element a CSS class based on its initial position */ 
function assignPositions() { 
    for (var i = 0; i < numberOfItems; i++) { 
     if (i === 0) { 
      itemPositions[i] = 'left-hidden'; 
     } else if (i === 1) { 
      itemPositions[i] = 'left'; 
     } else if (i === 2) { 
      itemPositions[i] = 'middle'; 
     } else if (i === 3) { 
      itemPositions[i] = 'right'; 
     } else { 
      itemPositions[i] = 'right-hidden'; 
     } 
    } 
    /* Add each class to the corresponding element */ 
    $('#scroller .item').each(function(index) { 
     $(this).addClass(itemPositions[index]); 
    }); 
} 

/* To scroll, we shift the array values by one place and reapply the classes to the images */ 
function scroll(direction) { 
    if (direction === 'prev') { 
     itemPositions.push(itemPositions.shift()); 
    } else if (direction === 'next') { 
     itemPositions.unshift(itemPositions.pop()); 
    } 
    $('#scroller .item').removeClass('left-hidden left middle right right-hidden').each(function(index) { 
     $(this).addClass(itemPositions[index]); 
    });   
} 

/* Do all this when the DOMs ready */ 
$(document).ready(function() { 

    assignPositions(); 



    /* Click behaviours */ 
    $('.left').click(function() { 
     scroll('prev'); 
    }); 
    $('.right').click(function() { 
     scroll('next'); 
    }); 
}); 

私は起こるしたい事は、ユーザが左または右の画像をクリックすると、ですが、私はそのイメージがセンター(または中央)に来てほしいです。 現在のシナリオでは、をクリックすると、イベントが1回だけ機能します。 誰でも助けてくれますか?

答えて

1

問題は、現在のセレクタでのイベントのみをバインドする機能です。今後の変更には適用されません。click

click機能の代わりにdelegate機能を使用する必要があります。ここで

が補正され、codepenワーキング:http://codepen.io/adrenalinedj/pen/JXazmy

そして、ここでは修正部分です:

$(document).ready(function() { 

    assignPositions(); 

    /* Click behaviours */ 
    $('#scroller').delegate(".left", "click", function() { 
     scroll('prev'); 
    }); 
    $('#scroller').delegate(".right", "click", function() { 
     scroll('next'); 
    }); 
}); 
+0

あなたはjQueryの1.7のよう 'on'の方法の代わりに、非推奨' delegate'メソッドを使用する必要があります – jontem

+0

@jontem 'delegate'は廃止予定ではありません(ドキュメント:http://api.jquery.com/delegate/を参照)。 'live'は廃止されました(ドキュメンテーション:http://api.jquery.com/live/を参照)。また、 'on'関数は、ここで問題となっている要素の現在選択されているセットのイベントだけをバインドします。 –

+0

@ ADreNaLiNe-DJありがとうございます。 – sairaj

関連する問題