How to move a carousel item to the middle when it's clicked in jquery

后端 未结 2 1873
夕颜
夕颜 2021-01-07 01:56

How can I make the carousel center the item I\'ve clicked to the middle? I\'ve looked everywhere for an answer but they\'re not straight answers... Can someone help me in th

相关标签:
2条回答
  • 2021-01-07 02:10

    Alright, it's ugly, I hope it gives you some ideas.

    I created a global currentItem that tracks what's in the center. Every time the carousel moves this is updated.

    The very useful variable I found was selfPosLeft which told me what was being clicked. I should add that 90 was the multiple I got from clicking around. Must be linked to your CSS and I don't know how to find this number dynamically.

    Please try it :) http://jsfiddle.net/sp9Jv/4/

    Well, I'm picturing that when you have more than 3 items you can change the code to compute the difference between the current item and the selfPosLeft of the clicked one, I'll leave that to you :) Like this, seems to work. http://jsfiddle.net/sp9Jv/5/

    0 讨论(0)
  • 2021-01-07 02:24

    While you have prepared all the information needed about all items, you can calculate the value of the left based on the clicked item.

    Here is my modification:

    and I've bound the click action of carousel items with this function and passed the clicked item using the self keyword.

    var itemClicked=function(item){
        var itemIndex=$(item).index(),
            newLeft=(itemIndex*itemWidth*-1)+Math.floor(($(viewport).width()/itemWidth)/2)*itemWidth;
        $(itemList).animate({left:newLeft+"px"},400);
    };
    

    You can check it working on this url: http://jsfiddle.net/rUZHg/3/

    I assume that this should work despite of the number of viewed elements while it calculates the padding between the left 0 and the left of the center element.

    0 讨论(0)
提交回复
热议问题