jQuery水平滚动(点击和动画)

我有一系列div在水平线上浮动到无限远。 我有一个固定宽度的div容器,溢出:隐藏。 最后,我想按左右两侧的div /按钮滚动项目(使用滚动条)。

我无法让.animate()工作。 我希望每次单击都可以移动列表中的项目。

它应该类似于亚马逊“购买此物品的顾客”列表,您可以以相同的方式滚动。 我很想尝试使用.mousedown并让它在移动时移动(类似于真正的滚动)但是想要先做更简单的方法。

这是小提琴和代码:

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

HTML:

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'}); }); }); 

任何和所有帮助赞赏。 谢谢!

添加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/

您的设置中还有一些错误,但这应该会让您失意。 🙂

编辑::

这是一个快速的解决方案,可以解决列表在任一方向上滑动太远的错误:

 $(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'}); } }); });