所以我有一堆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;
}
当左边距改变时整个滑块列表移动:
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);
}
});
});
当新元素作为最后添加时没有问题,当我尝试将其添加为第一个时 - 滑块列表移动。原因很明显,但是有什么方法可以避免这种情况吗?
答案 0 :(得分: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;
});