jQuery Horizontal Scrolling (click and animate)

后端 未结 1 1752
刺人心
刺人心 2020-12-30 11:28

I have a series of divs floating to infinity in a horizontal line. I have a fixed width div container them, overflow:hidden. Ultimately, I\'d like to press divs/buttons on l

相关标签:
1条回答
  • 2020-12-30 12:07

    Add position:relative to .item, like so:

    .item{
        background:green;
        width:140px;
        height:40px;
        margin:5px;
        float:left;
        position:relative; /* Put me here! */
    }
    

    Working example: http://jsfiddle.net/mattblancarte/stfzy/21/

    There are a few more bugs in your setup, but this should get you unstuck. :)

    Edit::

    Here is a quick solution to solve the bug where the list will slide too far in either direction:

    $(document).ready(function() {
    
        var $item = $('div.item'), //Cache your DOM selector
            visible = 2, //Set the number of items that will be visible
            index = 0, //Starting index
            endIndex = ( $item.length / visible ) - 1; //End index (NOTE:: Requires visible to be a factor of $item.length... You can improve this by rounding...)
    
        $('div#arrowR').click(function(){
            if(index < endIndex ){
              index++;
              $item.animate({'left':'-=300px'});
            }
        });
    
        $('div#arrowL').click(function(){
            if(index > 0){
              index--;            
              $item.animate({'left':'+=300px'});
            }
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题