无限轮播滚动溢出-x

时间:2012-05-30 06:05:59

标签: jquery scroll overflow infinite-scroll infinite-carousel

我有一个快速小提琴设置here。我想要的是能够无限滚动到左边或右边(旋转木马风格)并且只重复元素(即'脱落'右边缘并重新出现在左边,反之亦然) 。我能够捕捉到我在卷轴中的位置,但不确定之后的最佳方法是什么。在我尝试动态移动元素的路线之前,在我看来有一个非常简单的技巧。

CSS

#main {
    overflow-x:scroll;
    overflow-y:hidden;
    white-space:nowrap;
}

HTML

<div id="main">
    <img src="http://dummyimage.com/150x100/aaa/00f">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/000/fff">
    <img src="http://dummyimage.com/150x100/ccc/f00">
</div>

JS

$('#main').scroll(function (event) {
    var width = $(this)[0].scrollWidth - $(this).width();
    console.log('location: ' + $(this).scrollLeft() + ' out of ' + width);
});​

1 个答案:

答案 0 :(得分:3)

这相当不错,滚动条和所有:

$('#main').scroll(function (event) {
    var factor = this.scrollLeft / (this.scrollWidth - $(this).width());
    if(factor < 0.2) {
        var move = $(this.lastChild);
        move.remove();
        $(this).prepend(move);
        this.scrollLeft += move.width();
    } else if(factor > 0.8) {
        var move = $(this.firstChild);
        move.remove();
        $(this).append(move);
        this.scrollLeft -= move.width();
    }
});

jsFiddle:http://jsfiddle.net/ZgEZN/10/

滚动到最左边或最右边20%的滚动条会导致滚动条表现得很有趣,但不会出现剧烈的故障。 (将滚动条拖动到该区域会导致旋转木马快速旋转,直到滚动条被释放或移动到更合理的位置。以某种其他方式滚动到该区域会导致滚动条向中间跳回。)