2012-11-18 61 views
6

我有一系列div浮動到水平線無限。我有一個固定寬度的div容器他們,溢出:隱藏。最終,我想按左右的div /按鈕滾動項目(與使用滾動條)。jQuery水平滾動(點擊和動畫)

我無法讓.animate()工作。我希望每次點擊都可以將列表中的項目移動。

它應該類似於Amazons「購買此產品的顧客也購買」列表,您可以以相同的方式滾動瀏覽。我很想嘗試使用.mousedown,並讓它在按住時移動(類似於真正的滾動),但首先要做到這一點更簡單。

這裏是小提琴和代碼:

http://jsfiddle.net/stfzy/16/

HTML:

<div id="container"> 
<div id="arrowL"> 
</div> 
<div id="arrowR"> 
</div> 
<div id="list-container"> 
    <div class='list'> 
     <div class='item'> 
     </div> 
     <div class='item'> 
     </div> 
     <div class='item'> 
     </div> 
     <div class="item"> 
     </div> 
    </div> 
</div> 

CSS:

#container{ 
width:340px; 
    height:50px; 
} 

#list-container { 
overflow:hidden;  
width: 300px; 
float:left;  
} 

.list{ 
    background:grey; 
min-width:700px; 
    float:left; 
} 


#arrowR{ 
background:yellow; 
    width:20px; 
    height:50px; 
    float:right; 
    cursor:pointer; 
} 


#arrowL{ 
background:yellow; 
    width:20px; 
    height:50px; 
    float:left; 
    cursor:pointer; 
} 

.item{ 
    background:green; 
width:140px; 
    height:40px; 
    margin:5px; 
    float:left; 
} 

的jQuery

$(document).ready(function() { 

    $('div#arrowR').click(function(){ 

     $('div.item').animate({'left':'-=300px'}); 

    }); 

    $('div#arrowR').click(function(){ 

     $('div.item').animate({'left':'+=300px'}); 

    }); 

}); 

任何和所有的幫助表示讚賞。謝謝!

回答

17

添加position:relative.item,像這樣:

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

工作例如:http://jsfiddle.net/mattblancarte/stfzy/21/

,我們在您設置了幾個錯誤,但是這應該讓你脫膠。 :)

編輯::

這裏是一個快速的解決方案,以解決那裏的名單將在任一方向太遠滑動的bug:

$(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

真棒!我明白你對更多錯誤的含義......我假設你指的是我的列表有一個開始和結束的事實。但是,它需要循環纔能有效地工作。嗯...時間來弄清楚這一點。再次感謝。 – jstacks

+0

或者,也許我會導致箭頭按鈕禁用,當沒有更多的內容...可能是一個更好的選擇。 – jstacks

+0

@jstacks樂意幫忙!如果您尚未弄清楚,可以通過指定開始索引0來跟蹤滾動的位置,然後根據列表中的項目數來計算最大索引。如果你點擊分鐘,禁用左鍵。如果您達到最大值,請禁用右鍵。希望是有道理的!這不是唯一的解決辦法,但它是一個解決方案。 :) –