2013-07-25 65 views
1

我打算在一定的时间间隔前加上两个div来保存5个div的主div。当我添加一个新的div时,它应该隐藏列表中的最后一个div。预先一个div给隐藏最后一个孩子的div

在这里,我已经做出了小提琴http://jsfiddle.net/vivekdx/53aht/

的Html

<div class="container"> 
<div class="child">1</div> 
<div class="child">2</div> 
<div class="child">3</div> 
<div class="child">4</div> 
<div class="child">5</div> 
</div> 

CSS

.container{ width:300px; height:300px; background:#eee;} 
.child{ width:280px; margin:10px; height:40px; background:#ccc; float:left; text-align:Center; font-size:30px;} 

脚本

for (i = 0; i < 2; i++) 
{  
setInterval(function() 
    { 
$(".container").prepend('<div class="child">6</div>'); 
    }, 1000); 
} 

但它不工作好。

当我在前面加上6格5日必须墙根同样4格为7格...

,也是我没有正确循环它。引导我在这里

+0

的setInterval不应该使用!!!! 如果您的代码执行时间较长,那么时间间隔将会在未知的时间执行,并且可能会导致您期望的顺序不同。 例如:迭代#X已经开始,但是在它完成迭代#X + 1的启动和结束之前(因为间隔每X毫秒触发一次),所以结果将是#X + 1的输出,然后是#X。 查看http://jsfiddle.net/53aht/11/如何将您的代码转换为setTimeout。 – CodeWizard

回答

1

所以你只想要前五个元素可见。您可以使用jQuery slice()方法将集合限制为从第n个开始的所有元素。

// prepend a <div />, then get all the children, skip the first 5 and hide the rest. 
$(".container").prepend('<div class="child">6</div>').children().slice(5).hide(); 

更新小提琴:http://jsfiddle.net/53aht/4/

+0

谢谢你。我怎么能循环添加只有两个更多的div ...... – Jhonny

+0

你能澄清?如果你想在一定延迟后只添加两个div,那么你应该使用setTimeout。 – pawel

+0

是的,我试过它无限循环而不是停止在两个div – Jhonny

1

这里是你想要做什么。 http://jsfiddle.net/53aht/11/

但请记住,每当您添加新div时,您的DOM都在增长,因此请考虑从DOM删除(删除)它。

var counter = 10; 

function addDiv() { 
    $(".container").prepend('<div class="child">' + (++counter) + '</div>'); 
    setTimeout(addDiv, 1000); 
} 

addDiv(); 

CSS:

.container { 
    width:300px; 
    height:300px; 
    background:#eee; 
    overflow:hidden; 
} 
+0

谢谢。如何在预先挂上两个div后停止它并延迟第一个div – Jhonny

+0

是否有一种方法可以减慢隐藏和显示div – Jhonny

0

尝试是这样的:

for (i = 0; i < 2; ++i) 
{ 
    setTimeout(function() { 
     $(".container").prepend('<div class="child">6</div>').children().slice(5).hide(); 
    } , i * 1000); 
}