2012-03-03 72 views
0

我想在每次在我的数据库中找到新用户时插入一个新的div。如果我更改CSS(从类中删除“bottom”和“absolute”),我有以下代码工作。问题在于它从顶部开始,每个div插入到前一个下面。我想让div位于屏幕的左下角,然后在插入新div时向上移动。它基本上会推动现有的divs,而最新的div将会处于最底层。任何想法如何做到这一点?任何帮助,将不胜感激。谢谢!页面底部的动态div-Javascript

此代码将插入一个新的div,但它只是将它放在前一个之上。

.greyBox { 
    padding:8px; 
    background: grey; 
    margin-bottom:8px; 
    width:200px; 
    height:50px; 
    bottom:0; 
    position:absolute; 
} 
.redBox { 
    padding:8px; 
    background: red; 
    margin-bottom:8px; 
    width:200px; 
    height:25px; 
    bottom:1; 
    position:absolute; 
} 

<p> 
    <button id="after">New User</button> 
    <button id="reset">reset</button> 
</p> 

<div class="greyBox">Users</div> 

$("#after").click(function() { 
    $('.greyBox').after("<div class='redBox'>User 1</div>"); 
}); 

$("#reset").click(function() { 
    location.reload(); 
}); 

http://jsfiddle.net/ymTtB/

回答

1

添加一个新的带有“底部”类的div容器 http://jsfiddle.net/4np4q/

<html> 
<head> 
<script type="text/javascript" src="jquery.js"></script> 

<style type="text/css"> 
    .bottom{ 
    position: absolute; 
    bottom: 0;  
    } 
    .greyBox{ 
     padding:8px; 
     background: grey; 
     margin-bottom:8px; 
     width:200px; 
     height:50px; 

    } 

    .redBox{ 
     padding:8px; 
     background: red; 
     margin-bottom:8px; 
     width:200px; 
     height:25px; 
    } 
</style> 

</head> 
<body> 

    <p> 
    <button id="after">New User</button> 
    <button id="reset">reset</button> 
    </p> 

    <div class="bottom"> 
    <div class="greyBox">Users</div> 
</div> 
<script type="text/javascript"> 

    $("#after").click(function() { 
     $('.greyBox').after("<div class='redBox'>User 1</div>"); 
    }); 

    $("#reset").click(function() { 
     location.reload(); 
    }); 

</script> 
</body> 
</html> 
+0

工作就像一个魅力。谢谢! – mkyong 2012-03-03 15:31:10

+0

我用这个作为例子,我将需要消除按钮,因为div将自动创建。我怎样才能改变这个能够传递参数。我想我想让它成为一个单独的函数,可以从程序中调用,而不是点击。 – mkyong 2012-03-03 15:37:07

0

这是你position: absolute.redbox

.greyBox { 
    padding:8px; 
    background: grey; 
    margin-bottom:8px; 
    width:200px; 
    bottom:0; 
    position:absolute; 
} 

.redBox { 
    padding:8px; 
    background: red; 
    margin-bottom:8px; 
    width:200px; 
    height:25px; 
} 

而且,我以为你试图添加到.greyBox元素,而不是后。

$("#after").click(function() { 
    $('.greyBox').append("<div class='redBox'>User 1</div>"); 
}); 

$("#reset").click(function() { 
    $('.greyBox').children().remove(); 
}); 

http://jsfiddle.net/Bb6am/

如果你确实想.after()greyBox,你需要使用包装和应用 “底” 的风格吧:

.users { 
    width:200px; 
    bottom:0; 
    position:absolute; 
} 
.greyBox { 
    padding:8px; 
    background: grey; 
    margin-bottom:8px; 
} 

<p> 
    <button id="after">New User</button> 
    <button id="reset">reset</button> 
</p> 

$("#after").click(function() { 
    $('.greyBox').after("<div class='redBox'>User 1</div>"); 
}); 

$("#reset").click(function() { 
    $('.users').children().not('.greyBox').remove(); 
}); 

http://jsfiddle.net/Bb6am/2/