最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I auto scroll an unordered list horizontally? - Stack Overflow

programmeradmin4浏览0评论

I need to show two list items at a time and auto scroll to view all every n seconds.

I see lots of plex photo slider plugins, but what about simple text?

Here's a fiddle: /

HTML

<ul>
    <li>Lorem ipsum dolor sit amet</li>
    <li>Consectetur adipiscing elit</li>
    <li>Praesent modo nisi eu sapien</li>
    <li>Fusce tempor, sapien vitae tempus dapibus</li>
    <li>Aenean pulvinar urna vel tortor</li>
    <li>Proin turpis tellus, fringilla eget molestie nec</li>
    <li>Etiam sed varius lacus</li>
    <li>Aenean facilisis tincidunt massa luctus feugiat</li>
    <li>Etiam suscipit vel erat sit amet fringilla</li>
    <li>Nulla sit amet eros mauris.</li>
</ul>

CSS

ul {
    overflow-y: hidden;
    overflow-x: scroll;
    white-space: nowrap;
    padding:30px 0;
    margin:0;
}
li {
    display:inline;
    border:1px solid #ccc;
    padding:10px;
    margin:10px;
    list-style-type:none;
}

I need to show two list items at a time and auto scroll to view all every n seconds.

I see lots of plex photo slider plugins, but what about simple text?

Here's a fiddle: http://jsfiddle/B9DsX/

HTML

<ul>
    <li>Lorem ipsum dolor sit amet</li>
    <li>Consectetur adipiscing elit</li>
    <li>Praesent modo nisi eu sapien</li>
    <li>Fusce tempor, sapien vitae tempus dapibus</li>
    <li>Aenean pulvinar urna vel tortor</li>
    <li>Proin turpis tellus, fringilla eget molestie nec</li>
    <li>Etiam sed varius lacus</li>
    <li>Aenean facilisis tincidunt massa luctus feugiat</li>
    <li>Etiam suscipit vel erat sit amet fringilla</li>
    <li>Nulla sit amet eros mauris.</li>
</ul>

CSS

ul {
    overflow-y: hidden;
    overflow-x: scroll;
    white-space: nowrap;
    padding:30px 0;
    margin:0;
}
li {
    display:inline;
    border:1px solid #ccc;
    padding:10px;
    margin:10px;
    list-style-type:none;
}
Share Improve this question edited Sep 5, 2013 at 5:16 doppelgreener 5,13410 gold badges48 silver badges67 bronze badges asked Sep 5, 2013 at 5:07 RyanRyan 15.3k34 gold badges116 silver badges190 bronze badges 1
  • You could just apply the container styles from your fiddle directly to the ul - it'll work the same way. :) I've proposed an edit to include the CSS to make this example plete, and applied those styles directly to the ul to keep the example concise. – doppelgreener Commented Sep 5, 2013 at 5:17
Add a ment  | 

4 Answers 4

Reset to default 2

Here's a simple plugin function that will infinitely scroll list items:

Update Now two at a time:

$.fn.scrollList = function (delay) {
    delay = delay || 2000;
    var animateList = function ($list) {
        //get first child
        var $first = $list.children('li:first');
        var width = $first.outerWidth(true);
        //animate first two off the screen
        $first.animate({
            'margin-left': $list.width() * -1
        },
        // on animation plete
        function () {
            //reset and move to the end of the list
            $(this).css('margin-left', 0).add($(this).next()).appendTo($list);
            //start again after delay
            setTimeout(function () {
                animateList($list)
            }, delay);
        });
    };

    return this.each(function () {
        var $that = $(this)
        setTimeout(function () {
            animateList($that);
        }, delay);
    });

};

You can call it like this:

$('.container ul').scrollList(); 

Here's a demo fiddle

Note that to work correctly it requires some specific styles, most notably the items need margin-left:0 since that's the property being animated

Also you'll need to remove any whitespace between your <li> tags to avoid extra space between them, check this answer for different ways to do that

I just made a quick fiddle. This works but scrolling is not very smooth and the edges of li are visible but you get the idea. See demo

var liNum = 1;
var timerID;
var maxLi = 0;

$(function () {
    timerID = setInterval(scrollLi, 1000); //use 2500 for animation
    maxLi = $(".container ul li").length;
});

function scrollLi() {
    if (liNum >= maxLi) { //reset
        $(".container ul").scrollLeft(0);
        // use this for animation instead
        // $(".container ul").animate({scrollLeft: 0}, 1000);
        liNum = 1;
        //clearInterval(timerID);

    } else { //scroll next two li width
        var x = $(".container ul li:nth-child(" + liNum + ")").outerWidth(true);
        liNum++;
        x += $(".container ul li:nth-child(" + liNum + ")").outerWidth(true);
        liNum++;
        $(".container ul").scrollLeft($(".container ul").scrollLeft() + x);
        // use this line for animation instead
        // $(".container ul").animate({scrollLeft: $(".container ul").scrollLeft() + x}, 1500);
    }
}

Update: If you want scrollbars hidden use overflow: hidden and to make it scroll smoothly, you can use animate() as shown in this update DEMO. Note that I have changed the animation duration and the interval. Also mentioned the changes in above code as ments. You should play around with it and see what fits your needs better.

granted, this isn't exactly what you asked for - but it was fast to whip up. This is more of a fader, i hope you don't mind. You could sub an animate if you wish. Set the width of container to a different size and try this.

 var i = 0,
    container = $('ul li','.container');
    container.hide();
       (function fadeIt() {
         container.eq(i).fadeIn(2000).fadeOut(100, function() {
           i++;
           if(i % container.length == 0) {
             i = 0;
           }
          fadeIt();
        });
      }());

The tricks used in photo slideshows can be used on simple text as well. Some slideshows use relative-absolute positioning tricks. Here is my go at it:

.slideshow {
    position: relative;
    overflow: hidden;
}
.slideshow li {
    display: none;
    width: 50%;
}
.slideshow li.current {
    display: block;
    float: left;
}
.slideshow li.fadein {
    display: block;
    position: absolute;
    top: 0;
}
$(function() {
    // make the first two slides "current"
    $(".slideshow li:lt(2)").addClass("current");
    setInterval(function() {
        var current = $(".slideshow .current"); // current slides
        var slidein = $(".slideshow .current:last ~ li:lt(2)"); // next slides
        if (slidein.length == 0) {
            slidein = $(".slideshow li:lt(2)");
        }
        slidein.addClass("fadein"); // make visible, absolutely positioned
        slidein.eq(0).css({ left: "100%" }).animate({ left: 0 });
        slidein.eq(1).css({ left: "150%" }).animate({ left: "50%" }, function() {
            // reset and animate the "left" property
            // reset classes when animation is plete
            current.removeClass("current");
            slidein.removeClass("fadein").addClass("current");
        });
    }, 2000);
});

Demo here

发布评论

评论列表(0)

  1. 暂无评论