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

标签 jquery scroll click jquery-animate

我有一系列在水平线上无限 float 的 div。我有一个固定宽度的 div 容器,overflow:hidden。最后,我想按左右两侧的 div/按钮来滚动项目(相对于使用滚动条)。

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

它的工作方式应该类似于亚马逊的“购买此商品的顾客也购买了”列表,您可以以相同的方式滚动浏览。我很想尝试使用 .mousedown 并让它在按住时移动(类似于真正的滚动),但希望首先采用这种更简单的方法。

这是 fiddle 和代码:

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

    });

});

感谢所有帮助。谢谢!

最佳答案

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/

相关文章:

javascript - jQuery 在表循环中获取输入值

Jquery 可以在 JSfiddle 上运行,但不能在服务器上运行

macos - 为什么 NSTableView 可能会重绘滚动时的每个单元格?

java - 在Java中的非 Activity 窗口的某个位置模拟鼠标点击?

javascript - 使用自定义滚动条滚动部分(Nice Scroll)——快速滚动时动画效果不佳

Jquery UI 嵌套 Selectable 问题

javascript - 如何在固定宽度且带有水平滚动条的容器中放置 highcharts 图表?

javascript - 在水平滚动上更改 li 类

javascript - 单击的元素将其自身传递给将来的函数调用

python - Pygame 按钮单击