5

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

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);
});​
4

1 回答 1

5

这工作得相当好,滚动条和所有:

$('#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/

Scrolling to the leftmost or rightmost 20% of the scrollbar causes the scrollbar to behave funny, but not drastically glitchy. (Dragging the scrollbar to that area causes the carousel to spin rapidly until the scrollbar is either released or moved somewhere more reasonable. Scrolling to that area in some other way causes the scrollbar to jump back toward the middle.)

于 2012-05-30T07:57:13.713 回答