我有一系列在水平线上无限 float 的 div。我有一个固定宽度的 div 容器,overflow:hidden。最后,我想按左右两侧的 div/按钮来滚动项目(相对于使用滚动条)。
我无法让 .animate() 正常工作。我希望每次单击都能将列表中的项目移动。
它的工作方式应该类似于亚马逊的“购买此商品的顾客也购买了”列表,您可以以相同的方式滚动浏览。我很想尝试使用 .mousedown 并让它在按住时移动(类似于真正的滚动),但希望首先采用这种更简单的方法。
这是 fiddle 和代码:
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'});
});
});
感谢所有帮助。谢谢!
最佳答案
将 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'});
}
});
});
关于jQuery 水平滚动(点击和动画),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13438135/