Jquery UL Scroll



我正在尝试使用Jquery在UL列表上滚动,其中有两个span可以上下移动。它适用于一个li孩子,但对于一个动态填充的ul如何?谢谢,我完全迷路了

 $('span.scrollDown').click(function () {
        $('.liste-grostitres li:first-child').css('margin-top', 0 - $('.liste-grostitres li').outerHeight());
        $('.liste-grostitres').css('overflow', 'hidden');
    });
    $('span.scrollUp').click(function () {
        $('.liste-grostitres li:first-child').css('margin-top', 0);
        $('.liste-grostitres').css('overflow', 'visible');
    });

<div id="grostitres">
    <div class="gInner">
    <span class="scrollUp"></span>
    <span class="scrollDown"></span>
    <div class="scrollable" id="divlist" runat="server">   
      <ul>
          <li></li>
          <li></li>
          ...
      </ul>
    </div>              
    </div>

这里有一个滑块:http://jsfiddle.net/RMQLM/

还有工作代码示例:

HTML:

<div id="up">up</div>
<div id="list">
<ul>
    <li>foo1</li>
    <li>bar1</li>
    <li>foo2</li>
    <li>bar2</li>
    <li>foo3</li>
    <li>bar3</li>
    <li>foo4</li>
    <li>bar4</li>
    <li>foo5</li>
</ul>
</div>
<div id="down">down</div>

CSS:

div#list {
    height: 93px;
    overflow: hidden;
    border: 1px solid red;
}

jQuery:

var listcount = $('li').size();
var cli = 1;
$('#down').click(function() {
    if (cli < listcount) {
        $('li:nth-child(' + cli + ')').slideToggle();
        cli++;
    }
});
$('#up').click(function() {
    if (cli > 1) {
        cli--;
        $('li:nth-child(' + cli + ')').slideToggle();
    }
});

将UL设置为position: relative;并具有top: 0;

添加一个处理动画的函数:

var scroll_ul = function(offset) {
    // Target the UL to scroll
    var to_scroll = $('#divlist').find('ul');
    // Store the distance to scroll (assumes LIs are all equal height)
    var scroll_distance = $('#divlist').find('li').outerHeight(true);
    // Animate
    to_scroll.stop().animate({ top: '-=' + (offset * scroll_distance) });
};

然后把你的点击处理程序改成这样:

$('span.scrollDown').click(function() {
    scroll_ul(1);
});
$('span.scrollUp').click(function() {
    scroll_ul(-1);
});

如果按下scrollDown/scrollUp按钮,您可能会体验到奇怪的滚动距离。这时您应该研究jQuery的.one()函数。

我认为动画化整个UL而不是单个LI会更有效。您已经将UL包装在DIV中,那么为什么不相对于包装器设置UL动画呢?这将以与在UL内为单个LI设置动画相同的方式工作,因此您不需要重新发明轮子。

最新更新