1

所以我有一堆 li 元素看起来像:

<div id="previous_button">
    <a href="javascript:void(0)" id="previous">Previous</a>
</div>
<div id="slider-stage">
    <ul id="slider-list">
        <li>First</li>
        <li>Second</li>
        <li>Third</li>
        <li>Fourth</li>
        <li>Fifth</li>
        <li>Sixth</li>
    </ul>
</div>
<div id="next_button">
    <a href="javascript:void(0)" id="next">Next</a>
</div>

和 CSS:

#slider-stage
{
    float: left;
    width:825px;
    overflow:auto;
    overflow-x:hidden;
    overflow-y:hidden;
    height:235px;
    margin:0 auto;
}

#slider-list
{
    width: 1200px;
    border:0;
    margin:0;
    padding:0;
}

#slider-list li
{
    list-style:none;
    margin:0;
    padding:0;
    border:0;
    margin-right:15px;
    background: grey;
    background-size: 150px 235px;
    float:left;
    width:150px;
    height:235px;
}
#previous_button
{
    float: left;
    height: 235px;
    margin-right: 15px;
}
#next_button
{
    float: left;
    height: 235px;
    margin-right: 15px;
}

当 margin-left 改变时整个滑块列表移动:

window.addEvent('domready', function()
{ 
    var totIncrement = 0;
    var increment = 165;
    var maxRightIncrement = increment*(-2);
    var fx = new Fx.Tween('slider-list',
    {    
        duration: '500',
        property: 'margin-left'
    });
    // Previous Button
    document.id('previous').addEvent
    ('click', function(event)
    { 
        if(totIncrement<0)
        { 
            totIncrement = totIncrement + increment;
            fx.start(totIncrement);
        }
    }); 
    // Next Button
    document.id('next').addEvent
    ('click', function(event)
    { 
        special = special + 1;
        if(totIncrement>maxRightIncrement)
        { 
            totIncrement = totIncrement - increment;
            fx.start(totIncrement);
        }
    });
}); ​

当最后添加新元素时没有问题,当我尝试将它添加为第一个时 - 滑块列表移动。原因很明显,但是有什么办法可以避免呢?

4

1 回答 1

0

当您将新元素添加到列表的开头时,将margin-left新元素的宽度减小,有效地假装您向右滚动一次,从而使滑块保持在相同的位置:

$('new').addEvent('click', function(event) {
    Element('<li>New</li>', {text: 'New'})
        .inject($('slider-list'), 'top');
    $('slider-list').setStyle('margin-left', $('slider-list').getStyle('margin-left').toInt() - 165);
    totIncrement -= 165;
});

http://jsfiddle.net/kelervin/aZJTu/

于 2012-11-08T03:03:58.247 回答