我觉得这应该很简单,但我不知道该怎么做。
我想将新项目添加到列表顶部,然后让列表向下滚动以显示新项目。
到目前为止我得到的最接近的是:http://jsfiddle.net/philgyford/cmsh0zoz/4/这将通过执行以下操作创建并添加一个新列表项:
var content = 'Hello';
if (Math.random() < 0.3) {
content += '<br/>Another line';
};
$('<li>').html(content)
.hide()
.prependTo( $('ul') )
.slideDown('slow', function() {
// Remove final element:
$('ul').find('li:gt(9)').remove();
});
通过 slideDown
来显示新项目,这并不完全是我想要的 - 我希望它就像新项目出现在“测试列表”标题后面一样,并且然后整个列表向下滑动以显示它。
请注意,列表项具有不同的高度,这使事情稍微复杂化。
最佳答案
不要使用 slideDown
,而是考虑对 ul
的上边距进行动画处理,从新添加元素的负高度(包括填充)开始。
首先,将其添加到您的 h1
样式中:
position: relative;
这实际上将 h1
' 置于 ul
之上。 (请参阅 css positioning z-index negative margins 了解为什么我们不能为此使用 z-index。)
然后您可以像这样为ul
设置动画:
function scroll() {
var content = 'Hello';
if (Math.random() < 0.3) {
content += '<br/>Another line';
};
$('ul').prepend('<li>'+content)
.css('margin-top',-$('li').first().outerHeight(true))
.delay(1000)
.animate({'margin-top':0},
function() {
$(this).find('li:gt(9)').remove();
scroll();
}
);
};
在动画完成后调用 scroll
函数可能比使用 setInterval
更好,因为它保证在上一次滚动之前不会发生滚动。 延迟
使其无法连续运行。
关于javascript - 将项目添加到列表顶部并向下滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25971471/